<template>
  <div class="detail-container">
    <el-page-header :content="listItem ? '编辑' : '新增'" @back="goBack" />

    <div class="main-title">
      <div class="title">工程信息单</div>
    </div>

    <el-form
      ref="mainForm"
      :model="mainForm"
      :rules="mainFormRules"
      label-width="110px"
      size="small"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程登录编号" prop="orderNum">
            <el-input v-model="mainForm.orderNum" placeholder="系统自动生成" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8" style="height: 51px">
          <el-form-item label="单据日期" prop="orderDate">
            <el-date-picker
              v-model="mainForm.orderDate"
              disabled
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="系统自动生成"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="业务员" prop="salesMan">
            <el-select
              v-model="mainForm.salesMan"
              placeholder="选择业务员"
              size="small"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in salesmanList"
                :key="item.adminUserId"
                :label="item.nickName"
                :value="item.adminUserId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="产品大类" prop="mainId">
            <el-select v-model="mainForm.mainId" placeholder="选择产品大类" style="width: 100%">
              <el-option v-for="item in typeList" :key="item.dictCode" :label="item.dictValue" :value="item.dictCode"></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="经销商编码" prop="jxsNum">
            <el-input v-model="mainForm.jxsNum" placeholder="选择经销商" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="项目名称" prop="enginName">
            <el-input v-model="mainForm.enginName" placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="机型类别" prop="machineType">
            <el-select
              v-model="mainForm.machineType"
              placeholder="选择机型类别"
              size="small"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in machineTypeList"
                :key="item.dictCode"
                :label="item.dictValue"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="经销商名称" prop="jxsNum">
            <el-select
              v-model="mainForm.jxsNum"
              placeholder="选择经销商"
              size="small"
              filterable
              clearable
              style="width: 100%"
              :disabled="listItem != undefined"
              @change="changeDealer"
            >
              <el-option v-for="item in dealerList" :key="item.id" :label="item.name" :value="item.number" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="使用单位" prop="company">
            <el-input v-model="mainForm.company" placeholder="请输入使用单位" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="行业类别" prop="tradeCategory">
            <el-select
              v-model="mainForm.tradeCategory"
              placeholder="选择行业类别"
              size="small"
              clearable
              style="width: 100%"
            >
              <el-option v-for="item in tradeCategoryList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程编号" prop="enginNum">
            <div style="display: flex">
              <el-input v-model="mainForm.enginNum" placeholder="请输入工程编号" />
              <el-button
                style="margin-left: 10px"
                @click="
                  () => {
                    if (!this.mainForm.loginType) return this.$errorMsg('请选择工程登录类型')
                    this.visible = true
                    this.getLoginOrderList()
                  }
                "
                >引用</el-button
              >
            </div>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="厂工程编码" prop="factoryNum">
            <el-input v-model="mainForm.factoryNum" placeholder="请输入厂工程编码" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程登录类型" prop="loginType">
            <el-select
              v-model="mainForm.loginType"
              placeholder="选择工程登录类型"
              size="small"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in loginTypeList"
                :key="item.dictCode"
                :label="item.dictValue"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="联系人" prop="linkman">
            <el-input v-model="mainForm.linkman" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="mainForm.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="固定电话" prop="tel">
            <el-input v-model="mainForm.tel" placeholder="请输入固定电话" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="16" :lg="16">
          <el-form-item label="安装地址" prop="address">
            <el-input v-model="mainForm.address" placeholder="请输入安装地址" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="8" :lg="8">
          <el-form-item label="文件编号" prop="fileNo">
            <el-input v-model="mainForm.fileNo" placeholder="请输入文件编号" />
          </el-form-item>
        </el-col>
        <el-col v-if="!isDealer" :xs="24" :sm="24" :lg="16">
          <el-form-item label="格力内部备注" prop="greeRemark">
            <el-input v-model="mainForm.greeRemark" placeholder="请输入格力内部备注" />
          </el-form-item>
        </el-col>
        <el-col v-if="!isDealer" :xs="24" :sm="12" :lg="8">
          <el-form-item label="权限分类" prop="power">
            <el-select v-model="mainForm.power" placeholder="选择权限分类" size="small" clearable style="width: 100%">
              <el-option
                v-for="item in powerList"
                :key="item.dictCode"
                :label="item.dictValue"
                :value="item.dictCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="格力回复" prop="greeReply">
            <el-input
              v-model="mainForm.greeReply"
              :placeholder="isDealer ? '' : '请输入格力回复'"
              :disabled="isDealer"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="mainForm.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="制单人" prop="createMan">
            <el-input v-model="mainForm.createMan" placeholder="请输入制单人" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8" style="height: 51px">
          <el-form-item label="制单日期" prop="createDate">
            <el-date-picker
              v-model="mainForm.createDate"
              type="date"
              disabled
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8" style="height: 51px">
          <el-form-item label="合同有效期" prop="contractDate">
            <el-date-picker
              v-model="mainForm.contractDate"
              :disabled="isDealer"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="main-title">
      <div class="title">货品信息</div>
      <div>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="openDialog">添加货品</el-button>
        <el-divider direction="vertical" />
        <!-- <ImportButton :imUrl="'engin-info-order/import-item'" @importSuccess="getImportList" :isIcon="false" style="display: inline-block" />
        <ExportButton :exUrl="'engin-info-order/download'" :exParams="{}" :exText="'下载导入模版'" :isIcon="false" style="display: inline-block" /> -->
      </div>
    </div>

    <div class="table" style="margin-top: 20px">
      <el-table
        :data="goodsList"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        stripe
        show-summary
        :summary-method="$getSummaries"
        max-height="400"
      >
        <el-table-column align="center" label="序号" type="index" width="50" />
        <el-table-column align="center" label="销售类型" prop="saleTypeName" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select
              v-if="listItem"
              v-model="scope.row.saleTypeId"
              placeholder="选择销售类型"
              size="mini"
              clearable
              style="width: 100%"
              @change="changeSaleType(scope.$index)"
            >
              <el-option v-for="item in salesTypeList" :key="item.id" :label="item.saleName" :value="item.id" />
            </el-select>
            <div v-else>{{ scope.row.saleTypeName }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="物料编码" prop="materialNumber" min-width="120" show-overflow-tooltip />
        <el-table-column
          align="center"
          label="产品编码"
          prop="materialOldNumber"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column align="center" label="产品名称" prop="materialName" min-width="160" show-overflow-tooltip />
        <el-table-column align="center" label="规格型号" prop="specification" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-if="listItem" v-model="scope.row.specification" size="mini" />
            <div v-else>{{ scope.row.specification }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="单位" prop="unit" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" label="单价" prop="price" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.price" size="small" type="number" @mousewheel.native.prevent />
          </template>
        </el-table-column>
        <el-table-column align="center" label="数量" prop="qty" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model.number="scope.row.qty" size="small" type="number" @mousewheel.native.prevent />
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单金额" prop="myTotalAmount" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ (scope.row.price || 0) * (scope.row.qty || 0) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark" min-width="200" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" size="small" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="税率" prop="taxRate" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="deleteItem(scope.$index, scope.row, scope.row.cid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-footer">
      <div class="footer">
        <el-button type="primary" :loading="btnLoading" @click="clickSubmitForm(1)">保 存</el-button>
        <!--        <el-button type="primary" @click="clickSubmitForm(2)">提交审核</el-button>-->
        <el-popconfirm title="确定关闭吗？" style="margin-left: 10px" @confirm="goBack">
          <el-button slot="reference">返回列表</el-button>
        </el-popconfirm>
      </div>
    </div>
    <el-dialog
      title="添加产品"
      :modal-append-to-body="true"
      :append-to-body="true"
      :visible.sync="isShowGoodsDialog"
      width="80%"
    >
      <el-form ref="goodsScreenForm" :model="goodsScreenForm" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="salesType">
              <el-select v-model="goodsScreenForm.salesType" placeholder="选择销售类型" style="width: 100%" clearable>
                <el-option v-for="item in salesTypeList" :key="item.id" :label="item.saleName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proNum">
              <el-input
                @keyup.enter.native="submitGoodsScreenForm"
                v-model="goodsScreenForm.proNum"
                placeholder="请输入产品编码"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proName">
              <el-input
                @keyup.enter.native="submitGoodsScreenForm"
                v-model="goodsScreenForm.proName"
                placeholder="请输入产品名称"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="proModel">
              <el-input
                @keyup.enter.native="submitGoodsScreenForm"
                v-model="goodsScreenForm.proModel"
                placeholder="请输入产品型号"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="price1" style="display: flex">
              <el-input
                @keyup.enter.native="submitGoodsScreenForm"
                v-model="goodsScreenForm.price1"
                placeholder="请输入价格"
                style="width: 46%"
              />
              <span> - </span>
              <el-input
                @keyup.enter.native="submitGoodsScreenForm"
                v-model="goodsScreenForm.price2"
                placeholder="请输入价格"
                style="width: 46%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="18" :lg="18" class="tr">
            <el-form-item label="">
              <el-button size="small" @click="resetGoodsScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitGoodsScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="tables">
        <div class="table">
          <el-table
            :data="leftGoodsList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            stripe
            height="400"
            @selection-change="leftSelectionChange"
          >
            <el-table-column align="center" type="selection" width="55" :selectable="checkboxSelect" />
            <el-table-column align="center" label="销售类型" prop="saleName" show-overflow-tooltip />
            <el-table-column align="center" label="产品编码" prop="number" min-width="100" show-overflow-tooltip />
            <el-table-column align="center" label="产品名称" prop="name" min-width="160" show-overflow-tooltip />
            <el-table-column
              align="center"
              label="产品型号"
              prop="specification"
              min-width="160"
              show-overflow-tooltip
            />
            <el-table-column align="center" label="产品价格" prop="batchPrice" min-width="80" show-overflow-tooltip />
          </el-table>
          <div class="pagination clearfix" style="margin-top: 10px">
            <div class="fr">
              <el-pagination
                :current-page="currentPage"
                :page-size="10"
                background
                layout="prev, pager, next"
                :total="listTotal"
                @current-change="handleTableCurrentChange"
              />
            </div>
          </div>
        </div>
        <div class="buttons">
          <el-button size="small" type="primary" @click="addAllGoods">全部添加</el-button>
          <el-button size="small" type="primary" @click="addGoods">添&emsp;加</el-button>
          <el-button size="small" type="danger" @click="deleteGoods">删&emsp;除</el-button>
          <el-button size="small" type="danger" @click="deleteAllGoods">全部删除</el-button>
        </div>
        <div class="table">
          <el-table
            :data="rightGoodsList"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            stripe
            height="400"
            @selection-change="rightSelectionChange"
          >
            <el-table-column align="center" type="selection" width="55" />
            <el-table-column align="center" label="产品编码" prop="number" min-width="100" show-overflow-tooltip />
            <el-table-column align="center" label="产品名称" prop="name" min-width="160" show-overflow-tooltip />
            <el-table-column
              align="center"
              label="产品型号"
              prop="specification"
              min-width="160"
              show-overflow-tooltip
            />
            <el-table-column align="center" label="产品价格" prop="batchPrice" min-width="80" show-overflow-tooltip />
            <el-table-column align="center" prop="saleName" label="销售类型" show-overflow-tooltip />
          </el-table>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitAddGoods">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="商用工程登录项目"
      :visible.sync="visible"
      width="60%"
      :modal-append-to-body="true"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="onClose"
    >
      <div>
        <el-row :gutter="20">
          <el-form ref="formData" :model="formData" label-width="0" :inline="false" size="small">
            <el-col :span="18">
              <el-form-item prop="projectNo">
                <el-input v-model="formData.projectNo" placeholder="请输入项目编号" />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item prop="projectName">
                <el-input v-model="formData.projectName" placeholder="请输入项目名称" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="address">
                <el-input v-model="formData.address" placeholder="请输入项目地址" />
              </el-form-item>
            </el-col> -->
            <el-col :span="6" style="text-align: right">
              <el-button
                size="small"
                @click="
                  currentPage2 = 1
                  getLoginOrderList()
                "
                >查询</el-button
              >
              <el-button size="small" type="primary" @click="resetGoodsScreenForm2">重置</el-button></el-col
            >
          </el-form>
        </el-row>
        <div>
          <zj-table
            ref="tableEl"
            style="margin-bottom: 20px"
            :is-drop="true"
            :columns="columns"
            :table-data="tableData"
            :table-attributes="{
              border: true,
              maxHeight: '600px'
            }"
          />
          <div class="fr">
            <el-pagination
              :current-page="currentPage2"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="listTotal2"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
      <span slot="footer">
        <el-button @click="onClose">取 消</el-button>
        <el-button type="primary" @click="submitAddOrder">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEnginDetail,
  getRetailProductList,
  addEngin,
  editEngin,
  submitEngin,
  delItem,
  getLoginOrderList
} from '@/api/supply/engin'
import { getDictList, getTypeList, getSalesmanList, getDealerList } from '@/api/common'

export default {
  name: 'EnginForm',
  componentName: 'EnginForm',
  props: ['listItem'],
  data() {
    return {
      goodsList: [],
      mainForm: {
        orderNum: '',
        orderDate: '',
        // mainId: '102',
        jxsNum: '',
        enginName: '',
        machineType: '',
        jxsName: '',
        jxsId: '',
        company: '',
        address: '',
        enginNum: '',
        factoryNum: '',
        loginType: '',
        linkman: '',
        phone: '',
        tel: '',
        remark: '',
        salesMan: '',
        createMan: '',
        createDate: '',
        contractDate: '',
        tradeCategory: '',
        power: '',
        greeRemark: '',
        greeReply: '',
        fileNo: ''
      },
      mainFormRules: {
        salesMan: [{ required: true, message: '请选择业务员', trigger: 'change' }],
        jxsNum: [{ required: true, message: '请输入经销商编码', trigger: 'blur' }],
        enginName: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        jxsName: [{ required: true, message: '请输入经销商名称', trigger: 'blur' }],
        company: [{ required: true, message: '请输入使用单位', trigger: 'blur' }],
        address: [{ required: true, message: '请输入安装地址', trigger: 'blur' }],
        enginNum: [{ required: true, message: '请输入工程编号', trigger: 'blur' }],
        loginType: [{ required: true, message: '请输入工程登录类型', trigger: 'blur' }],
        tradeCategory: [{ required: true, message: '请选择行业类别', trigger: 'change' }]
      },
      loginTypeList: [],
      powerList: [],
      machineTypeList: [],
      tradeCategoryList: [
        { value: '房地产', label: '房地产' },
        { value: '公共建筑', label: '公共建筑' },
        { value: '工业制造', label: '工业制造' },
        { value: '商业项目', label: '商业项目' },
        { value: '采暖及清洁能源', label: '采暖及清洁能源' },
        { value: '轨道交通', label: '轨道交通' },
        { value: '数据通讯', label: '数据通讯' },
        { value: '冷冻冷藏', label: '冷冻冷藏' },
        { value: '高端制造', label: '高端制造' },
        { value: '医院医疗', label: '医院医疗' },
        { value: '其他', label: '其他' }
      ],
      btnLoading: false,
      typeList: [],
      salesTypeList: [],
      salesmanList: [],
      dealerList: [],

      isShowGoodsDialog: false,
      goodsScreenForm: {
        proNum: '',
        proName: '',
        proModel: '',
        price1: '',
        price2: '',
        salesType: ''
      },
      currentPage: 1,
      listTotal: 0,

      leftGoodsList: [],
      rightGoodsList: [],

      leftSelection: [],
      rightSelection: [],
      examineStatus: '',
      visible: false,
      currentPage2: 1,
      pageSize2: 10,
      listTotal2: 0,
      formData: {
        address: '',
        projectName: '',
        projectNo: ''
      },
      tableData: [],
      current: ''
    }
  },

  computed: {
    isDealer() {
      return JSON.parse(localStorage.getItem('supply_user')).isCustomer
    },
    columns() {
      return [
        {
          columnAttributes: {
            label: '操作',
            width: 45
          },
          render: (h, { row, column, index }) => {
            return (
              <div>
                <el-radio
                  style="margin-left:20px"
                  value={this.current}
                  label={row.id}
                  onChange={val => {
                    this.current = row.id
                  }}
                >
                  {}
                </el-radio>
              </div>
            )
          }
        },
        {
          columnAttributes: {
            label: '项目编号',
            prop: 'projectNo',
            width: 100
          }
        },
        {
          columnAttributes: {
            label: '项目名称',
            prop: 'projectName',
            width: 200
          }
        },
        {
          columnAttributes: {
            label: '项目地址',
            prop: 'address'
          }
        }
      ]
    }
  },
  watch: {
    goodsList: {
      deep: true,
      immediate: true,
      handler(val, oval) {
        val.forEach(item => {
          item.myTotalAmount = (item.price || 0) * (item.qty || 0)
          item.sums1 = ['number', 'directTransferQty', 'qty', 'enginNum', 'oldQty', 'hasSendQty']
          item.sums2 = ['myTotalAmount', 'payAmount', 'price', 'payRebateAmount', 'discAmount']
        })
      }
    }
  },
  async created() {
    await this.getSalesmanList()
    this.getDictList()
    this.getTypeList()
    this.getDealerList()
    if (this.listItem) {
      this.getDetail()
    } else {
      this.mainForm.jxsNum = JSON.parse(localStorage.getItem('supply_user')).customerNumber
      this.mainForm.jxsName = JSON.parse(localStorage.getItem('supply_user')).customerName
      this.mainForm.createMan = JSON.parse(localStorage.getItem('supply_user')).nickName
      this.mainForm.createDate = this.getDate(0)
      this.mainForm.contractDate = this.getDate(1)
    }
  },

  methods: {
    // 返回列表
    goBack() {
      this.$emit('backListFormDetail')
    },
    getLoginOrderList() {
      getLoginOrderList({
        pageNum: this.currentPage2,
        pageSize: this.pageSize2,
        ...this.formData,
        orderType: this.mainForm.loginType
      }).then(res => {
        this.tableData = res.data.records
        this.listTotal2 = res.data.total
      })
    },
    getDate(addYear) {
      var date = new Date()
      var seperator1 = '-'
      var year = date.getFullYear() + addYear
      var month = date.getMonth() + 1
      var strDate = date.getDate()
      if (month >= 1 && month <= 9) {
        month = '0' + month
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate
      return currentdate
    },

    // 获取详情
    getDetail() {
      getEnginDetail({ id: this.listItem.enginInfoId }).then(res => {
        const data = res.data
        this.mainForm.orderNum = data.enginInfoNo
        this.mainForm.orderDate = data.orderDate
        // this.mainForm.mainId = data.productCategoryId;
        this.mainForm.jxsNum = data.customerNumber
        this.mainForm.enginName = data.projectName
        this.mainForm.machineType = data.machineType
        this.mainForm.jxsName = data.customerName
        this.mainForm.company = data.useUnit
        this.mainForm.tradeCategory = data.tradeCategory
        this.mainForm.address = data.installAddress
        this.mainForm.enginNum = data.projectNo
        this.mainForm.factoryNum = data.enginFactoryNo
        this.mainForm.loginType = data.enginSignType
        this.mainForm.linkman = data.linkman
        this.mainForm.phone = data.phone
        this.mainForm.tel = data.tel
        this.mainForm.remark = data.remark
        this.mainForm.salesMan = data.serviceId
        this.mainForm.serviceName = data.serviceName
        this.mainForm.createMan = data.createName
        this.mainForm.createDate = data.createTime
        this.mainForm.contractDate = data.contractExpireDate
        this.mainForm.power = data.powerCategory
        this.mainForm.greeRemark = data.geLiInerNote
        this.mainForm.greeReply = data.geLiNote
        this.mainForm.fileNo = data.fileNo
        this.examineStatus = data.examineStatus
        data.items.forEach(item => {
          item.cantDel = true
          item.cid = item.id
        })

        this.goodsList = data.items
      })
    },

    // 获取经销商列表
    getDealerList() {
      getDealerList({
        pageNum: 1,
        pageSize: -1
        // bindUser: false
      }).then(res => {
        this.dealerList = res.data.records
      })
    },

    // 获取产品大类列表
    getDictList() {
      getDictList({ sysDictEnum: 'PRODUCT_TYPE' }).then(res => {
        this.typeList = res.data
      })
      getDictList({ sysDictEnum: 'MACHINE_TYPE' }).then(res => {
        this.machineTypeList = res.data
      })
      getDictList({ sysDictEnum: 'POWER_CATEGORY' }).then(res => {
        this.powerList = res.data
      })
      getDictList({ sysDictEnum: 'SIGN_TYPE' }).then(res => {
        this.loginTypeList = res.data
      })
    },

    // 获取销售类型列表
    getTypeList() {
      getTypeList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.salesTypeList = res.data.records
      })
    },

    async getSalesmanList() {
      const res = await getSalesmanList({
        pageNum: 1,
        pageSize: -1,
        isCustomer: 0,
        status: true
      })
      this.salesmanList = res.data.records
      console.log(this.salesmanList)
    },

    changeDealer() {
      if (this.mainForm.jxsNum) {
        const jxsItem = this.dealerList.find(o => o.number == this.mainForm.jxsNum)
        this.mainForm.jxsName = jxsItem.name
        this.mainForm.jxsId = jxsItem.id
      } else {
        this.mainForm.jxsName = ''
        this.mainForm.jxsId = ''
      }
    },

    changeSaleType(index) {
      if (this.goodsList[index].saleTypeId) {
        const obj = this.salesTypeList.find(o => o.id == this.goodsList[index].saleTypeId)
        this.goodsList[index].saleTypeName = obj.saleName
        this.goodsList[index].saleTypeCode = obj.saleCode
      } else {
        this.goodsList[index].saleTypeName = ''
        this.goodsList[index].saleTypeCode = ''
      }
    },

    // 获取商品列表
    getGoodsList() {
      console.log(this.goodsList, '000')
      getRetailProductList({
        pageNum: this.currentPage,
        pageSize: 10,
        saleId: this.goodsScreenForm.salesType,
        materialCode: this.goodsScreenForm.proNum,
        materialName: this.goodsScreenForm.proName,
        specification: this.goodsScreenForm.proModel,
        price1: this.goodsScreenForm.price1,
        price2: this.goodsScreenForm.price2,
        customerId: this.listItem ? this.listItem.customerId : ''
      }).then(res => {
        console.log(res.data.records)
        const oldGoodsList = this.goodsList
        const newGoodsList = res.data.records
        for (let i = 0; i < oldGoodsList.length; i++) {
          const oldItem = oldGoodsList[i]
          for (let j = 0; j < newGoodsList.length; j++) {
            const newItem = newGoodsList[j]
            if (
              `${newItem.materialNumber}_${newItem.saleTypeId}` === `${oldItem.materialNumber}_${oldItem.saleTypeId}`
            ) {
              newGoodsList[j].selected = true
              break
            }
          }
        }
        res.data.records.forEach(item => {
          item.materialName = item.name
          item.materialCode = item.number
          item.saleTypeName = item.saleName
          item.unit = item.baseUnit
          item.price = item.batchPrice
          item.tax = item.taxRate
          item.isDirectTransfer = false
          item.directTransferQty = ''
          item.status1 = ''
          item.status2 = ''
          item.rebateAmount = ''
          item.rebateRate = ''
          item.productPriceId = item.id
          // item.customerWalletId = (item.wallets && item.wallets.length) ? item.wallets[0].customerWalletId : '';
        })
        this.leftGoodsList = res.data.records
        this.listTotal = res.data.total
      })
    },

    // 查询重复值并禁选
    checkboxSelect(row, rowIndex) {
      if (row.selected) {
        return false // 禁用
      } else {
        return true // 不禁用
      }
    },

    // 点击 选择商品
    openDialog() {
      this.isShowGoodsDialog = true
      this.getGoodsList()
    },

    // 提交筛选表单
    submitGoodsScreenForm() {
      this.currentPage = 1
      this.getGoodsList()
    },

    // 重置筛选表单
    resetGoodsScreenForm() {
      this.$refs.goodsScreenForm.resetFields()
      this.currentPage = 1
      this.getGoodsList()
    },

    // 更改列表当前页
    handleTableCurrentChange(val) {
      this.currentPage = val
      this.getGoodsList()
    },

    // 关闭 弹窗
    closeDialog() {
      this.isShowGoodsDialog = false
    },

    // 左侧列表选择
    leftSelectionChange(val) {
      this.leftSelection = val
    },

    // 右侧列表选择
    rightSelectionChange(val) {
      this.rightSelection = val
    },

    // 数组去重
    delRepeat(arr1, arr2) {
      const allArr = arr1.concat(arr2) // 两个数组对象合并
      const newArr = [] // 存放去重后数据的新数组
      for (let i = 0; i < allArr.length; i++) {
        // 循环allArr数组对象的内容
        let flag = true // 建立标记，判断数据是否重复，true为不重复
        for (let j = 0; j < newArr.length; j++) {
          // 循环新数组的内容
          if (allArr[i].id == newArr[j].id) {
            // 让allArr数组对象的内容与新数组的内容作比较，相同的话，改变标记为false
            flag = false
          }
        }
        if (flag) {
          // 判断是否重复
          newArr.push(allArr[i]) // 不重复的放入新数组。  新数组的内容会继续进行上边的循环。
        }
      }
      return newArr
    },

    // 全部添加
    addAllGoods() {
      this.rightGoodsList = this.delRepeat(this.leftGoodsList, this.rightGoodsList)
    },

    // 添加
    addGoods() {
      this.rightGoodsList = this.delRepeat(this.leftSelection, this.rightGoodsList)
    },

    // 删除
    deleteGoods() {
      const rightGoodsList = this.rightGoodsList
      const rightSelection = this.rightSelection
      for (let i = 0; i < rightGoodsList.length; i++) {
        for (let j = 0; j < rightSelection.length; j++) {
          if (rightSelection[j].materialId == rightGoodsList[i].materialId) {
            this.rightGoodsList.splice(i, 1)
          }
        }
      }
    },

    // 全部删除
    deleteAllGoods() {
      this.rightGoodsList = []
    },

    // 确定 添加产品
    submitAddGoods() {
      // this.goodsList = this.delRepeat(this.rightGoodsList, this.goodsList);

      this.goodsList = this.goodsList.concat(this.rightGoodsList)
      this.goodsList.forEach(k => {
        if (!k.qty) {
          k.qty = 0
        }
        if (!k.cid) {
          k.cid = ''
        }
      })
      this.isShowGoodsDialog = false
      this.leftGoodsList = []
      this.rightGoodsList = []
    },

    // 删除产品
    deleteItem(index, row, id) {
      // id id存在就说明这个货品已经引用过了
      // if (this.listItem && this.examineStatus === 'OK' && id) {
      //   this.$errorMsg('已审核通过的型号不能删除')
      //   return
      // }
      if (id) {
        delItem({
          enginInfoNo: row.enginInfoNo,
          itemId: row.id
        }).then(res => {
          this.goodsList.splice(index, 1)
          this.$successMsg('存在的货品删除成功')
        })
      } else {
        this.goodsList.splice(index, 1)
        this.$successMsg('删除成功')
      }
    },

    // 导入产品
    getImportList(data) {
      this.goodsList = this.goodsList.concat(data)
    },

    clickSubmitForm(type) {
      this.btnLoading = true
      this.$refs.mainForm.validate(valid => {
        if (valid) {
          for (let i = 0; i < this.goodsList.length; i++) {
            if (!this.goodsList[i]?.saleTypeId) {
              this.$errorMsg('请选择销售类型')
              return
            }
            if (this.goodsList[i]?.qty == null || this.goodsList[i]?.qty === '' || Number(this.goodsList[i]?.qty) < 0) {
              this.$errorMsg('数量不能为空或者小于0')
              return
            }
            if (!this.goodsList[i]?.materialNumber) {
              return
            }
          }

          const goodsList = JSON.parse(JSON.stringify(this.goodsList))

          goodsList.forEach(item => {
            delete item.productList
            delete item.id
          })
          const saleManItem = this.mainForm.salesMan
            ? this.salesmanList.find(o => o.adminUserId == this.mainForm.salesMan)
            : ''
          const params = {
            // orderDate: this.mainForm.orderDate + ' 00:00:00',
            // mainId: this.mainForm.mainId,
            projectName: this.mainForm.enginName,
            machineType: this.mainForm.machineType,
            useUnit: this.mainForm.company,
            tradeCategory: this.mainForm.tradeCategory,
            installAddress: this.mainForm.address,
            projectNo: this.mainForm.enginNum,
            enginFactoryNo: this.mainForm.factoryNum,
            enginSignType: this.mainForm.loginType,
            linkman: this.mainForm.linkman,
            phone: this.mainForm.phone,
            serviceId: this.mainForm.salesMan,
            serviceName: saleManItem?.nickName || (this.mainForm.salesMan ? this.mainForm.serviceName : '') || '',
            tel: this.mainForm.tel,
            remark: this.mainForm.remark,
            contractExpireDate: this.mainForm.contractDate,
            powerCategory: this.mainForm.power,
            geLiInerNote: this.mainForm.greeRemark,
            geLiNote: this.mainForm.greeReply,
            fileNo: this.mainForm.fileNo,
            items: goodsList
          }
          console.log(params)
          if (type === 1) {
            if (this.listItem) {
              params.enginInfoId = this.listItem.enginInfoId
              editEngin(params)
                .then(res => {
                  this.$successMsg('编辑成功')
                  this.goBack()
                })
                .finally(() => {
                  this.btnLoading = false
                })
            } else {
              params.customerNumber = this.mainForm.jxsNum
              params.customerName = this.mainForm.jxsName
              params.customerId = this.mainForm.jxsId
              addEngin(params)
                .then(res => {
                  this.$successMsg('保存成功')
                  this.goBack()
                })
                .finally(() => {
                  this.btnLoading = false
                })
            }
          } else {
            if (this.listItem) {
              params.enginInfoId = this.listItem.enginInfoId
            } else {
              params.customerNumber = this.mainForm.jxsNum
              params.customerName = this.mainForm.jxsName
              params.customerId = this.mainForm.jxsId
            }
            submitEngin(params)
              .then(res => {
                this.$successMsg('提交审核成功')
                this.goBack()
              })
              .finally(() => {
                this.btnLoading = false
              })
          }
        }
      })
    },
    handleSizeChange(val) {
      this.pageSize2 = val
      this.currentPage2 = 1
      this.getLoginOrderList()
    },
    handleCurrentChange(val) {
      this.currentPage2 = val
      this.getLoginOrderList()
    },
    // 重置筛选表单
    resetGoodsScreenForm2() {
      this.$refs.formData.resetFields()
      this.currentPage2 = 1
      this.getLoginOrderList()
    },
    submitAddOrder() {
      const item = this.tableData.find(k => k.id === this.current)
      this.mainForm.enginNum = item.projectNo
      this.mainForm.enginName = item.projectName
      this.mainForm.linkman = item.enginLinkName
      this.mainForm.phone = item.enginLinkMobile
      this.mainForm.address = item.joinAddress

      this.onClose()
    },
    onClose() {
      this.$nextTick(() => {
        this.current = ''
        this.$refs.formData.resetFields()
        this.visible = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
.detail-container {
  width: 100%;
  height: 100%;
}

.main-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  height: 60px;
  border-bottom: 1px solid #dcdfe6;
  margin-bottom: 20px;

  .title {
    font-size: 16px;
    font-weight: 600;
    padding-left: 10px;
  }
}

.tables {
  display: flex;
  margin-top: 10px;

  .table {
    width: 45%;
  }

  .buttons {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 0 10px;

    button {
      margin: 0;
      margin-top: 10px;
    }
  }
}

::v-deep input::-webkit-outer-spin-button,
::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

::v-deep input[type='number'] {
  -moz-appearance: textfield;
}
</style>
