<!--总成模块信息管理页 pg-M100BIll -->
<template>
  <div class="cr-body-content">
    <div ref="box">
    <flexbox class="content-header" >
      <el-form
        :model="listQuery"
        ref="queryForm"
        v-show="showSearch"
        :inline="true"
      >
        <el-form-item label="生产线:" prop="productLine">
          <el-select
            v-model="listQuery.productLine"
            clearable
            placeholder="请选择"
            size="medium"
            style="margin-right: 15px"
            @change="valueselectChange"
          >
          <el-option
            v-for="item in PLChildList"
            :key="item.id"
            :label="item.productLineName"
            :value="item.productLineCode"/>
          </el-select>
        </el-form-item>

          <el-form-item label="版本:" prop="Version">
            <el-input
              v-model="listQuery.Version"
              placeholder=""
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
      <!-- </el-row> -->
      <!-- <el-row> -->
        <el-form-item label="大众顺序号:" prop="HostSNBegin">
          <el-input
            v-model="listQuery.HostSNBegin"
            placeholder=""
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="-" prop="HostSNEnd">
          <el-input
            v-model="listQuery.HostSNEnd"
            placeholder=""
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="KNR:" prop="KNRBegin" >
          <el-input
            v-model="listQuery.KNRBegin"
            placeholder=""
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="-" prop="KNREnd">
          <el-input
            v-model="listQuery.KNREnd"
            placeholder=""
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      <!-- </el-row> -->
      <!-- <el-row> -->
        <el-form-item label="底盘号:" prop="VINBegin">
          <el-input
            v-model="listQuery.VINBegin"
            placeholder=""
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="-" prop="VINEnd">
          <el-input
            v-model="listQuery.VINEnd"
            placeholder=""
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="上线日期">
          <el-date-picker
            v-model="listQuery.OnlineTimeValue"
            size="small"
            style="width: 380px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange" :default-time="['00:00:00','23:59:59']"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
      <!-- </el-row> -->
      <!-- <el-row> -->
        <el-form-item label="接收日期" >
          <el-date-picker
            v-model="listQuery.ReceiveTimeValue"
            size="small"
            style="width: 380px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange" :default-time="['00:00:00','23:59:59']"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item >
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleFilter"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery('queryForm')"
            >重置</el-button
          >
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            style="margin-left: 15px"
            @click="handleDownload()"
            >导出(Excel)
          </el-button>
        </el-form-item>
      <!-- </el-row> -->
        <!-- <el-divider class="divider1" ></el-divider> -->
        <el-form-item style="margin-bottom: 0px;margin-top: -1px">
          <el-button
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="handleCreate"
            >新增
          </el-button>
          <el-button
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate"
            >修改
          </el-button>
          <el-button
            class="filter-item"
            size="mini"
            type="primary"
            icon="el-icon-delete"
            @click="handleDelete"
            >删除
          </el-button>
        </el-form-item>
      </el-form>
    </flexbox>
    </div>
    <div class="l-table" style="margin-top: -9px">
      <!--表格渲染-->
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        element-loading-text="拼命加载中..."
        element-loading-spinner="el-icon-loading"
        class="cr-table"
        :data="list"
        :height="tableHeight"
        :cell-style="cellStyle"
        :header-cell-style="headerRowStyle"
        size="small"
        stripe
        border
        highlight-current-row
        style="width: 100%"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
      >
        
        <el-table-column
          label="底盘号"
          prop="vin "
          sortable="custom"
          align="center"
          
          width="180px"
        >
          <template slot-scope="scope">
            <span class="link-type" @click="handleDrawerOpen(scope.row)">{{
              scope.row.vin
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in getDefaultField"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :min-width="item.width"
          :formatter="fieldFormatter"
          sortable="custom"
          show-overflow-tooltip
          :gutter="0"
        >
          <template slot="header" slot-scope="scope">
            {{ scope.column.label }}
          </template>
        </el-table-column>
      </el-table>

      <!--表单渲染-->
      <el-dialog
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        :title="formTitle"
        width="1000px"
      >
        <el-form
          ref="form"
          :inline="true"
          :model="form"
          :rules="rules"
          size="small"
          label-width="120px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="KNR:" prop="knr" required >
                <el-select
                  style="width: 350px"
                  v-model="form.knr"
                  placeholder="请选择添加M100信息对应的KNR号"
                  filterable
                  :disabled="false"
                  @change="getVModel"
                >
                  <el-option
                    v-for="item in KNRlist"
                    :key="item.knr"
                    :label="item.knr"
                    :value="item.knr"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="车型:" prop="vehicleModelCode" required >
                <el-select
                  style="width: 350px"
                  v-model="form.vehicleModelCode"
                  :disabled="false"
                  @change="vMchange"
                >
                  <el-option
                    v-for="item in vehicleModelList"
                    :key="item.id"
                    :label="item.dicItemName"
                    :value="item.dicItemCode"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="底盘号:"  prop="vin" required >
                <el-input
                  style="width: 350px"
                  v-model="form.vin"
                  :disabled="false"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="大众顺序号:"  prop="hostSN" required >
                <el-input
                  style="width: 350px"
                  v-model="form.hostSN"
                  :disabled="false"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上线日期:" prop="onlineTime" required>
              <el-date-picker
                v-model="form.onlineTime"
                style="width: 350px"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择时间"
                :disabled="false"
              >
              </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <div style="border:1px solid #E4E4E4;width:94%">
                <el-row>
                  <div style="background:#F1F1F1;width:100%;height:30px;line-height:31px;">
                    <label style="margin-left:15px">ERP总成</label>
                  </div>
                </el-row>
                <el-row>
                  <el-table
                    ref="LeftDetialTable"
                    v-loading="listLoading"
                    element-loading-text="拼命加载中..."
                    element-loading-spinner="el-icon-loading"
                    class="cr-table"
                    :data="form.leftdetails"
                    :height="detailTableHeight"
                    :cell-style="cellStyle"
                    :header-cell-style="headerRowStyle"
                    size="small"
                    stripe
                    border
                    highlight-current-row
                    style="width: 95%;margin:10px"
                    @row-click="handleLeftRowClick"
                    @selection-change="handleLeftSelectionChange"
                  >
                    <!-- <el-table-column type="selection" width="44px"></el-table-column> -->
                    <el-table-column prop="erpAssemblyCode" label="ERP总成编号" width="150px" > 
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.erpAssemblyCode" size="mini" style="width:135px"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="erpAssemblyName" label="ERP总成名称">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.erpAssemblyName" size="mini"></el-input>
                      </template> 
                    </el-table-column>
                    <el-table-column  width="35px"> 
                      <template slot="header">
                        <el-button @click="handleAddLeftDetails" icon="el-icon-plus" type="text"></el-button>
                      </template>
                      <template slot-scope="scope">
                        <el-button @click="handleLeftDeleteDetails(scope.$index, scope.row)" icon="el-icon-minus" type="text"></el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-row>
                <!-- <el-divider class="divider2"  content-position="left">添加ERP总成</el-divider>
                <el-row>
                  <el-form-item label="ERP总成编码:" prop="erpAssemblyCode"  >
                    <el-input
                      style="width: 315px"
                      v-model="form.erpAssemblyCode"
                      :disabled="isEdit"
                      placeholder="请输入总成编码"
                    />
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="ERP总成名称:" prop="erpAssemblyName"  >
                    <el-input
                      style="width: 315px"
                      v-model="form.erpAssemblyName"
                      :disabled="isEdit"
                      placeholder="请输入总成名称"
                    />
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="车型:" prop="vehicleModel"  >
                    <el-select
                      style="width: 315px"
                      v-model="form.vehicleModel"
                      :disabled="isEdit"
                      placeholder="请输入总成名称"
                    >
                      <el-option
                        v-for="item in vehicleModelList"
                        :key="item.id"
                        :label="item.dicItemName"
                        :value="item.dicItemCode"/>
                    </el-select>
                  </el-form-item>
                </el-row>
                <div style="text-align:center;margin: 0px;margin-bottom: 15px;">
                  <el-button type="primary" @click="leftclick">添加总成</el-button>
                </div> -->
              </div>
            </el-col>
            <el-col :span="12">
              <div style="border:1px solid #E4E4E4;width:94%">
                <el-row>
                  <div style="background:#F1F1F1;width:100%;height:30px;line-height:31px;">
                    <label style="margin-left:15px">ERP结算件</label>
                  </div>
                </el-row>
                <el-row>
                  <el-table
                    ref="DetialTable"
                    v-loading="listLoading"
                    element-loading-text="拼命加载中..."
                    element-loading-spinner="el-icon-loading"
                    class="cr-table"
                    :data="form.rightdetails"
                    :height="detailTableHeight"
                    :cell-style="cellStyle"
                    :header-cell-style="headerRowStyle"
                    size="small"
                    stripe
                    border
                    highlight-current-row
                    style="width: 95%;margin:10px"
                  >
                    <!-- <el-table-column type="selection" width="44px"></el-table-column> -->
                    <el-table-column prop="partCode" label="客户零件代码" width="150px" > 
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.partCode" size="mini" style="width:135px"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="description" label="客户零件名称">
                      <template slot-scope="scope">
                        <el-input v-model="scope.row.description" size="mini"></el-input>
                      </template> 
                    </el-table-column>
                    <el-table-column prop="partNum" label="客户零件数量" width="120px" >
                      <template slot-scope="scope">
                        <el-input-number v-model="scope.row.partNum" :min="1"  size="mini" style="width:100px"></el-input-number>
                      </template>
                    </el-table-column>
                    <el-table-column width="35px"> 
                      <template slot="header">
                        <el-button @click="handleAddRightDetails" icon="el-icon-plus" type="text"></el-button>
                      </template>
                      <template slot-scope="scope">
                        <el-button @click="handleRightDeleteDetails(scope.$index, scope.row)" icon="el-icon-minus" type="text"></el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-row>
                <!-- <el-divider class="divider2"  content-position="left">添加ERP结算件</el-divider>
                <el-row>
                  <el-form-item label="客户零件代码:" prop="customerPartCode"  >
                    <el-input
                      style="width: 315px"
                      v-model="form.customerPartCode"
                      :disabled="isEdit"
                      placeholder="请输入客户零件代码"
                    />
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="客户零件名称:" prop="customerPartName"  >
                    <el-input
                      style="width: 315px"
                      v-model="form.customerPartName"
                      :disabled="isEdit"
                      placeholder="请输入总成名称"
                    />
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="数量:" prop="partQty"  >
                    <el-input-number
                      style="width: 315px"
                      v-model="form.partQty"
                      :disabled="isEdit"
                      :min="1"
                    />
                  </el-form-item>
                </el-row>
                <div style="text-align:center;margin: 0px;margin-bottom: 15px;">
                  <el-button type="primary">添加零件</el-button>
                </div> -->
              </div>
            </el-col>
          </el-row>
        </el-form>
        <!--表格渲染-->
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="dialogFormVisible = false"
            >取消</el-button
          >
          <el-button v-loading="formLoading" type="primary" @click="save"
            >确认</el-button
          >
        </div>
      </el-dialog>
    </div>

    <div class="table-footer">
      <!-- 分页控件 style="margin-top: -25px;margin-bottom:-25px;float:right;"-->
      <pagination
        v-show="totalCount > 0"
        :total="totalCount"
        :page.sync="page"
        :limit.sync="listQuery.MaxResultCount"
        @pagination="getList"
      />
      <!-- 抽屉控件 -->
      <el-drawer
        title="信息详细页"
        size="75%"
        direction="rtl"
        :visible.sync="drawer"
        :before-close="handleDrawerClose"
      >
        <div>
          <Detail
            v-bind:customerInfos="customerInfos"
            style="margin-top: -35px"
          ></Detail>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import permission from "@/directive/permission/index.js";
import CRMTableHead from "../../components/CRMTableHead";
import importExcel from "@/components/ImportExcel-vw";
import Lockr from "lockr";
import moment from "moment";
import { mapGetters } from 'vuex';
import Detail from "./detail.vue";
import { downloadFile } from "@/utils/crmindex.js";

//组件计量单位
const bomUnit = [
  { key: 0, display_name: "PC" },
  { key: 1, display_name: "TON" },
  { key: 2, display_name: "Other" },
];
const projectTypeKeyValue = bomUnit.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "m100Bill",
  components: { Pagination, CRMTableHead, importExcel, Detail },
  directives: { permission },
  filters: {
    IsCustomerSignFilter(status) {
      //翻译是否签字
      const statusMap = {
        true: "是",
        false: "否",
      };
      return statusMap[status];
    },
  },
  data() {
    const validVersion = (rule, value, callback) => {
      let numberReg = /^\d{6}$/;
      if (!numberReg.test(value)) {
        callback(new Error("只能为6位数字！"));
      } else {
        callback();
      }
    };
    return {
      crmType: "m100Bill",
      rules: {
        erpAssemblyName: [
          { required: true, message: "必须输入！", trigger: "blur" },
        ],
      },
      valueSelect: "",
      customerInfos: [],
      dialogOptions: [],
      versionValue: "",
      searchContent: "", // 输入内容
      showExcelImport: false,
      form: {},
      drawer: false,
      list: null,
      totalCount: 0,
      listLoading: true,
      customerInfo: {
        bomId: "",
      },
      // 高级搜索
      filterObj: {
        type: Object,
        default: () => {
          return {};
        },
      },
      listQuery: {
        SkipCount: 0,
        MaxResultCount: 15,
        ProductLine: undefined,
        version:undefined,
        HostSNBegin:undefined,
        HostSNEnd:undefined,
        KNRBegin:undefined,
        KNREnd:undefined,
        VINBegin:undefined,
        VINEnd:undefined,
        OnlineTimeValue:undefined,
        OnlineTimeBegin:undefined,
        OnlineTimeEnd:undefined,
        ReceiveTimeValue:undefined,
        ReceiveTimeBegin:undefined,
        ReceiveTimeEnd:undefined,

      },
      listExportQuery: {
        erpAssemblyCode: undefined,
        erpAssemblyName: undefined,
      },
      listPLQuery:{
        BillType: 2,
        //UserId: "00000000-0000-0000-0000-000000000000",
      },
      knrQuery:{ 
        knr: undefined,
      },
      form:
      {
        leftdetails:[],
        rightdetails:[],
      },
      saveform:{
        m100Bill:
        {
          knr:undefined,
          vehicleModelCode:undefined,
          vin:undefined,
          hostSN:undefined,
          onlineTime:undefined,
          billStatus:2,
          billM100Parts:[],
        },
        erpAssemblyList:
        [
          // {
          //   erpAssemblyCode:undefined,
          //   erpAssemblyName:undefined,
          //   vehicleModel:undefined,
          //   //isCover: true,
          //   details: undefined,
          //     // {
          //     //   partCode: undefined,
          //     //   partNum: 1,
          //     //   description: undefined,
          //     //   isKey: false
          //     // }
          // },
        ]
        
        // #region
        /*
        
        */
       //  #endregion
      },
      rightAlldetails:[],
      page: 1,
      // 显示搜索条件
      showSearch: true,
      bomUnit,
      multipleSelection: [],
      multipLeLeftSelection:[],
      drawer: false,
      dialogFormVisible: false,
      formTitle: "",
      isEdit: false,
      formLoading: false,
      tableHeight: document.documentElement.clientHeight - 335,
      detailTableHeight:250,
      //details:[], //修改子表数据源
      PLList:[],//产线下拉
      PLChildList:[],//筛选后产线下拉
      vehicleModelQuery:{
        dicTypeName:"车型",
      },
      vehicleModelList:[],//车型list
      gettime:"",
      KNRlist:null,
    };
  },
  mounted() {
    this.$nextTick(() => { 
        var offsetHei = document.documentElement.clientHeight;
        //console.log(offsetHei);
        let boxH = this.$refs.box.offsetHeight;
        this.tableHeight = offsetHei - boxH - 57 - 79;//57为footer高度，79为页面上部标签高度
        //console.log(this.$refs.box.offsetHeight);
        //console.log(this.tableHeight);
    });
  },
  created() {
    //this.getKNRList();
    this.getProductLine();
    //this.getList();
    //console.log(this.userInfo);
  },
  computed: {
    getDefaultField() {
      
      var tempsTabs = [];
      tempsTabs.push({ label: "流水号", prop: "serialNum", width: 100 });
      tempsTabs.push({ label: "大众顺序号", prop: "hostSN", width: 120 });
      tempsTabs.push({
        label: "KNR",
        prop: "knr",
        width: 130,
      });
      // tempsTabs.push({
      //   label: "底盘号",
      //   prop: "vin",
      //   width: 130,
      // });
      tempsTabs.push({
        label: "上线时间",
        prop: "onlineTime",
        width: 150,
      });
      tempsTabs.push({
        label: "接收时间",
        prop: "receiveTime",
        width: 180,
      });
      tempsTabs.push({
        label: "车型代码",
        prop: "vehicleModelCode",
        width: 120,
      });
      tempsTabs.push({
        label: "版本",
        prop: "version",
        width: 150,
      });
      tempsTabs.push({
        label: "采集点",
        prop: "collectionPoint",
        width: 120,
      });
      tempsTabs.push({
        label: "文件名称",
        prop: "fileName",
        width: 120,
      });
      tempsTabs.push({
        label: "产线",
        prop: "productLine",
        width: 120,
      });
      return tempsTabs;
    },
    ...mapGetters(['userInfo'])//获取当前用户信息
  },
  methods: {
    //抽屉
    handleDrawerOpen(param) {
      this.drawer = true;
      //console.log(param)
      var parentId = param.assemblyID; //主键id
      this.customerInfos = [
        {
          ParentId: parentId,
        },
      ];
    },
    handleDrawerClose(done) {
      done();
    },
    getCurrentTime() {
        //获取当前时间并打印
        var _this = this;
        let yy = new Date().getFullYear();
        let month =  new Date().getMonth()+1;
        let mm = month<10 ? '0'+month : month;
        let dd = new Date().getDate()<10 ? '0'+new Date().getDate() : new Date().getDate();
        let hh = new Date().getHours()<10 ? '0'+new Date().getHours() : new Date().getHours();
        let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
        let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
        _this.gettime = yy+'-'+mm+'-'+dd+' '+hh+':'+mf+':'+ss;
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.saveform.m100Bill.hostSN = this.form.hostSN;
          this.saveform.m100Bill.knr = this.form.knr;
          this.saveform.m100Bill.vin = this.form.vin;
          this.saveform.m100Bill.onlineTime = this.form.onlineTime;
          this.saveform.m100Bill.vehicleModelCode = this.form.vehicleModelCode;
          this.getCurrentTime();
          this.saveform.m100Bill.description = "无";
          this.saveform.m100Bill.receiveTime = this.gettime;
          //判断最后一次右侧数据rightdetails是否在右侧全部数据rightAlldetails中
          this.form.rightdetails.forEach(element => {
            var tlist = this.rightAlldetails.filter(u => u.erpAssemblyCode === element.erpAssemblyCode && u.partCode === element.partCode 
                                          && u.partName === element.partName && u.partNum === element.partNum);
            if(tlist.length === 0)
            {
              this.rightAlldetails.push(element);
            }
          });

          //this.saveform.erpAssemblyList.details = {};
          //console.log("当前左侧数据");
          //console.log(this.form.leftdetails);
          //console.log("当前右侧显示数据");
          //console.log(this.form.rightdetails);
          //console.log("当前右侧全部数据");
          //console.log(this.rightAlldetails);

          /**左右关联拼接最终erpAssemblyList格式 */
          this.form.leftdetails.forEach((element,i) => {
            var templist = this.rightAlldetails.filter(u => u.erpAssemblyCode === element.erpAssemblyCode);
            let obj = {};
            obj.erpAssemblyCode = element.erpAssemblyCode;
            obj.erpAssemblyName = element.erpAssemblyName;
            obj.vehicleModel = element.vehicleModel;
            obj.details = [];

            templist.forEach(detail => {
              if(detail.partCode !== "" && detail.partCode !== undefined)
              {
                obj.details.push(detail);
              }
            });
            this.saveform.erpAssemblyList.push(obj);
          });

          //console.log(this.saveform);
          console.log("保存参数:" + JSON.stringify(this.saveform));
          this.formLoading = true;
          if (this.isEdit) {
            //修改
            this.$axios
              .puts("/api/newjit/new-m100/" + this.multipleSelection[0].id,this.saveform)
              .then((response) => {
                console.log(response);
                this.formLoading = false;
                this.$notify({
                  title: "成功",
                  message: "更新成功",
                  type: "success",
                  duration: 2000,
                });
                this.dialogFormVisible = false;
                this.getList();
              })
              .catch(() => {
                this.formLoading = false;
                console.log("error");
                this.saveform = {
                  m100Bill:
                  {
                    knr:undefined,
                    vehicleModelCode:undefined,
                    vin:undefined,
                    hostSN:undefined,
                    onlineTime:undefined,
                    billStatus:2,
                    billM100Parts:[],
                  },
                  erpAssemblyList:[],
                };
                this.dialogFormVisible = false;
                this.getList();
              });
          } else {
            //insert添加
            console.log(JSON.stringify(this.saveform));
            this.$axios
              .posts("/api/newjit/new-m100", this.saveform)
              .then((response) => {
                this.formLoading = false;
                this.$notify({
                  title: "成功",
                  message: "新增成功",
                  type: "success",
                  duration: 2000,
                });
                this.dialogFormVisible = false;
                this.getList();
              })
              .catch(() => {
                this.formLoading = false;
                this.saveform = {
                  m100Bill:
                  {
                    knr:undefined,
                    vehicleModelCode:undefined,
                    vin:undefined,
                    hostSN:undefined,
                    onlineTime:undefined,
                    billStatus:2,
                    billM100Parts:[],
                  },
                  erpAssemblyList:[],
                };
              });
          }
        }
      });
    },
    /** 新增 */
    handleCreate() {
      this.getKNRList();
      if (this.$refs["form"] !== undefined) {
        this.$nextTick(() => {
          this.$refs["form"].resetFields();
        });
      }
      this.formTitle = "新增";
      this.isEdit = false;
      this.form = {};
      this.rightAlldetails = [];
      this.saveform = {
        m100Bill:
        {
          knr:undefined,
          vehicleModelCode:undefined,
          vin:undefined,
          hostSN:undefined,
          onlineTime:undefined,
          billStatus:2,
          billM100Parts:[],
        },
        erpAssemblyList:[],
      };
      //this.details = [];
      this.getvehicleModel();
      this.dialogFormVisible = true;
    },
    /** 修改 */
    handleUpdate(row) {
      this.getKNRList();
      this.formTitle = "修改";
      this.isEdit = true;
      this.rightAlldetails = [];
      this.saveform = {
        m100Bill:
        {
          knr:undefined,
          vehicleModelCode:undefined,
          vin:undefined,
          hostSN:undefined,
          onlineTime:undefined,
          billStatus:2,
          billM100Parts:[],
        },
        erpAssemblyList:[],
      };
      //this.details = [];
      this.getvehicleModel();
        if (this.multipleSelection.length != 1) {
          this.$message({
            message: "编辑必须选择单行",
            type: "warning",
          });
          return;
        } else {
          this.fetchData(this.multipleSelection[0].id);
          this.dialogFormVisible = true;
        }
    },
    /** 删除 */
    handleDelete(row) {
      if (this.multipleSelection.length != 1) {
          this.$message({
            message: "编辑必须选择单行",
            type: "warning",
          });
          return;
      }
        // this.$alert("暂时不支持批量删除", "提示", {
        //   confirmButtonText: "确定",
        //   callback: (action) => {
        //     //
        //   },
        // });  
        this.$confirm("是否删除底盘号" + this.multipleSelection[0].vin + "的数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          this.$axios
            .deletes("/api/newjit/new-m100/"+ this.multipleSelection[0].id)
            .then((response) => {
              const index = this.list.indexOf(this.multipleSelection[0]);
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
                duration: 2000,
              });
              this.getList();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    fetchData(id) {
      //循环动态
      this.$axios
        .gets("/api/newjit/new-m100/" + id)
        .then((response) => {
          //console.log(response);
          this.form = response.item.m100Bill;
          this.form.rightdetails = [];
          this.form.leftdetails = response.item.erpAssemblyList;
          response.item.erpAssemblyList.forEach((element,i) => {
            element.details.forEach(item => {
              item.erpAssemblyCode = element.erpAssemblyCode;
              this.rightAlldetails.push(item);
              if( i === 0 )
              {
                this.form.rightdetails.push(item);
              }
            });
            //console.log(this.rightAlldetails);
            //console.log(this.form.rightdetails);
          });
        });
    },
    /** 导出功能 */
    handleDownload() {
      this.listLoading = true;
      this.listExportQuery.erpAssemblyCode = this.listQuery.ErpAssemblyCode;
      this.listExportQuery.erpAssemblyName = this.listQuery.ErpAssemblyName;
      console.log(JSON.stringify(this.listExportQuery));
      this.$axios
        .posts("/api/newjit/new-m100/export", this.listExportQuery)
        .then((res) => {
          this.handleFilter()
          let filename = res.item;
          this.$axios
            .BolbGets("/api/newjit/exclude-part-cfg/download/" + filename)
            .then((response) => {
              if (filename.indexOf("_") != -1) {
                let downName =
                  filename.slice(0, filename.lastIndexOf("_")) +
                  filename.slice(filename.lastIndexOf("."));
                downloadFile(response, downName);
                this.$notify({
                  title: "成功",
                  message: "数据-导出成功！",
                  type: "success",
                  duration: 2000,
                });
              } else {
                downloadFile(response, filename);
                this.$notify({
                  title: "成功",
                  message: "数据-导出成功！",
                  type: "success",
                  duration: 2000,
                });
              }
              this.listLoading = false;
            });
        })
        .catch(err=>{
          this.handleFilter()
        })
    },
    /** 重置按钮操作 */
    resetQuery(refName) {
      this.$refs[refName].resetFields();
      this.listQuery.OnlineTimeValue = [];
      this.listQuery.ReceiveTimeValue = [];
      this.handleQuery();
      this.getProductLine();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.listQuery.SkipCount = 1;
      //this.getList();
    },
    selectValue(params) {
      //版本下拉选择
      this.versionValue = params.value;
      this.getList();
    },

    selectOptionsChange(item) {
      this.getList();
    },
    importExcelData() {
      //关闭导入窗体时调用
      this.showExcelImport = false;
      //this.getList();
    },

    /** 刷新列表 */
    handleHandle(data) {
      if (data.type !== "edit") {
        this.getList();
      }
    },

    /**左增加 */
    handleAddLeftDetails() {
      this.$forceUpdate();
      if (this.form.leftdetails === undefined) {
        this.form.leftdetails = [];
        //console.log(679);
      }
      let obj = {};
      obj.erpAssemblyCode = "";
      obj.erpAssemblyName = "";
      obj.vehicleModel = this.form.vehicleModelCode;

      //console.log(this.form.leftdetails);
      this.form.leftdetails.push(obj);
      //console.log(688);
    },
    /**右增加 */
    handleAddRightDetails() {
      this.$forceUpdate();
      let obj = {};
      //判断是否选择了左侧的数据
      //console.log(this.multipLeLeftSelection);
      if(this.multipLeLeftSelection.length !== 1)
      {
        this.$message({
            message: "必须选择单行总成",
            type: "warning",
          });
          return;
      }
      else
      {
        // if (this.form.rightdetails === undefined) {
        //   this.form.rightdetails = [];
        //   this.form.rightdetails.erpAssemblyCode = this.multipLeLeftSelection[0].erpAssemblyCode;
        //   //console.log(679);
        // }
      }
      obj.erpAssemblyCode = this.multipLeLeftSelection[0].erpAssemblyCode;
      obj.partCode = "";
      obj.description = "";
      obj.partNum= 1;

      //console.log(this.form.rightdetails);
      this.form.rightdetails.push(obj);
      //console.log(688);
    },
    /**左侧删除 */
    handleLeftDeleteDetails(index,row){
      this.form.leftdetails.splice(index, 1);
      this.rightAlldetails = this. rightAlldetails.filter(u => u.erpAssemblyCode !== row.erpAssemblyCode);
      //console.log(693);
    },
    /**右侧删除 */
    handleRightDeleteDetails(index,row){
      this.form.rightdetails.splice(index, 1);
      this.rightAlldetails.forEach((element,i) => {
        if(element === row)
        {
          //console.log("右侧删除");
          this.rightAlldetails.splice(i, 1);
          //console.log(this.rightAlldetails);
          return;
        }
      });
      // .filter(u => u.erpAssemblyCode !== row.erpAssemblyCode && u.partCode !== row.partCode 
      //                                             && u.partName !== row.partName && u.partNum !== row.partNum);
                                          
      //console.log(693);
    },

    /** 格式化字段 */
    fieldFormatter(row, column) {
      if (column.property === "billStatus") {
        return { 0: "未生效", 2: "已生效", 3: "已发布" }[row[column.property]];
      }
      if (column.property == "onlineTime" || column.property == "receiveTime") {
        var date = row[column.property];
        if (date == undefined) {
          return "";
        }
        return moment(date).format("YYYY-MM-DD HH:mm:ss");
      }
      return row[column.property] || "--";
    },
    roleFilter(type) {
      return projectTypeKeyValue[type];
    },
    getList(data) {
      this.listLoading = true;
        if (data != undefined) {
        this.listQuery.SkipCount = (this.page - 1) * data.limit;
      } else {
        this.listQuery.SkipCount = (this.page - 1) * 15;
      }
      if(this.listQuery.OnlineTimeValue!== undefined)
      {
        this.listQuery.OnlineTimeBegin = this.listQuery.OnlineTimeValue[0];
        this.listQuery.OnlineTimeEnd = this.listQuery.OnlineTimeValue[1];
      }
      if(this.listQuery.ReceiveTimeValue!== undefined)
      {
        this.listQuery.ReceiveTimeBegin = this.listQuery.ReceiveTimeValue[0];
        this.listQuery.ReceiveTimeEnd = this.listQuery.ReceiveTimeValue[1];
      }
      this.$axios
        .gets("/api/newjit/new-m100/list", this.listQuery)
        .then((response) => {
          this.list = response.items;
          this.totalCount = response.totalCount;
          setTimeout(() => {
            //大数据量加载时
            this.listLoading = false;
          }, 500);
        })
        .catch(() => {
          this.listLoading = false;
        });
    },

    getKNRList() {
      var lq = {};
      var tlist = [];
      this.$axios
        .gets("/api/newjit/bill-r100/list", lq)
        .then((response) => {
          this.KNRlist = response.items;
          console.log("获取R100的KNR信息");
          console.log(this.KNRlist);
        })
        .catch(() => {
          console.log("error");
        });
    },
    getVModel()
    {
      this.form.vehicleModelCode = this.KNRlist.filter(u => u.knr === this.form.knr)[0].vehicleModelCode;
      this.knrQuery.knr = this.form.knr;
      this.form.rightdetails = [];
      this.$axios
        .gets("/api/newjit/new-m100/get-erp-assembly-list", this.knrQuery)
        .then((response) => {
          if(response.status === true)
          {
            this.KNREClist = response.item;
            //console.log("获取KNR的总成信息");
            //console.log(this.KNREClist);
            this.form.leftdetails = response.item;
            this.$forceUpdate();
            response.item.forEach((element,i) => {
              element.details.forEach(detail => {
                detail.erpAssemblyCode = element.erpAssemblyCode;
                this.rightAlldetails.push(detail);
                if( i === 0 )
                {
                  this.form.rightdetails.push(detail);
                }
              });
            });
          }
          else
          {
            console.log("接口返回结果为错误");
          }
        })
        .catch(() => {
          console.log("error");
        });
    },
    vMchange()
    {
      this.$forceUpdate();
    },

    valueselectChange(){this.$forceUpdate();},
    handleImportSAP(){},

    handleFilter() {
      this.page = 1;
      this.getList();
    },

    sortChange(data) {
      const { prop, order } = data;
      if (!prop || !order) {
        this.handleFilter();
        return;
      }
      this.listQuery.Sorting = prop + " " + order;
      this.handleFilter();
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      //console.log(this.multipleSelection);
    },
    handleLeftSelectionChange(val)
    {
      // console.log("左改变");
      // console.log(val);
      // this.multipLeLeftSelection = [];
      // this.multipLeLeftSelection.push(val);
      // console.log(this.multipLeLeftSelection);
    },
    /** 通过回调控制style */
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property === "qty") {
        return { textAlign: "right" };
      } else {
        return { textAlign: "left" };
      }
    },
    /** 通过回调控制表头style */
    headerRowStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property === "qty") {
        return { textAlign: "right", background: "#FAFAFA" };
      } else {
        return { textAlign: "left", background: "#FAFAFA" };
      }
    },
    /**主表点击*/
    handleRowClick(row, column, event) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row);
    },
    /**左点击*/
    handleLeftRowClick(row, column, event) {
      this.$forceUpdate();
      //console.log("左点击");
      this.$refs.LeftDetialTable.clearSelection();
      this.$refs.LeftDetialTable.toggleRowSelection(row);
      this.multipLeLeftSelection = [];
      this.multipLeLeftSelection.push(row);
      if(this.form.rightdetails === undefined)
      {
        this.form.rightdetails = []
      }
      if(this.form.rightdetails.length > 0)
      {
        var templist = this.rightAlldetails.filter(u => u.erpAssemblyCode === this.form.rightdetails[0].erpAssemblyCode);
        this.form.rightdetails.forEach(element => {
          var temp = templist.filter(u => u.erpAssemblyCode === element.erpAssemblyCode && u.partCode === element.partCode 
                            && u.partName === element.partName && u.partNum === element.partNum);
          if(temp.length >= 1)
          {
            //console.log("判定包含");
            //console.log(templist);
            //console.log(element);
          }
          else
          {
            //console.log("判定不包含");
            //console.log(element);
            this.rightAlldetails.push(element);
          }
        });
      }
      else
      {
        var templist = [];
      }
      //.log("右侧全数据");
      //console.log(this.rightAlldetails);
      this.form.rightdetails = this.rightAlldetails.filter(u => u.erpAssemblyCode === this.multipLeLeftSelection[0].erpAssemblyCode);
      //console.log("右侧数据");
      //console.log(this.form.rightdetails);
    },
    //获取所有产线
    getProductLine()
    {
      this.listPLQuery.UserId = this.userInfo.userId;
      this.$axios
          .gets(
            "/api/newjit/product-line/list",this.listPLQuery
          )
          .then((response) => {
            //console.log(response);
            this.PLList = response.item;
            this.PLChildList = this.PLList.sort((a,b)=>{return a.productLineCode-b.productLineCode});
            this.listQuery.productLine = this.PLChildList[0].productLineCode;
            this.getList();
            
            //console.log(this.PLList);
          })
          .catch(() => {
          });
    },
    //获取车型
    getvehicleModel()
    {
      this.$axios
          .gets(
            "/api/newjit/dic/list",this.vehicleModelQuery
          )
          .then((response) => {
            //console.log(response);
            this.vehicleModelList = response.item;
            //console.log()
          })
          .catch(() => {
          });
    },
    leftclick()
    {
      this.$forceUpdate();
      let obj = {};
      obj.erpAssemblyCode = this.form.erpAssemblyCode;
      obj.erpAssemblyName = this.form.erpAssemblyName;
      obj.vehicleModel = this.form.vehicleModelCode;
      
      if (this.form.leftdetails === undefined) {
        this.form.leftdetails = [];
      }
      this.form.leftdetails.push(obj);
    },
    rightclick(){},
  },
};
</script>


<style lang="scss" scoped>
@import "../../../pg-fis/styles/crmtable.scss";

// /*表格全选框去除空框*/
// .el-table >>> .DisabledSelection .cell .el-checkbox__inner {
//   display: none;
//   position: relative;
// }
// /*表格全选框改为：选择*/
// .el-table >>> .DisabledSelection .cell:before {
//   content: "是否Key件";
//   position: absolute;
//   left: 7px;
// }
.divider1{
  margin: 0 ;
}
.divider2{
  margin: 10px;
  margin-bottom: 20px ;
  width: 95%;
}
</style>

