<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="选择业务员"
              disabled
              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="type">
            <el-select v-model="mainForm.type" placeholder="选择产品大类" style="width: 100%" disabled>
              <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="16">
          <el-form-item label="经销商名称" prop="jxsNum">
            <el-select
              v-model="mainForm.jxsNum"
              placeholder="选择经销商"
              size="small"
              filterable
              clearable
              style="width: 100%"
              :disabled="listItem != undefined || isDealer"
              @change="changeDealer"
            >
              <el-option v-for="item in dealerList" :key="item.number" :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="enginOrderNum">
            <div style="display: flex">
              <el-input v-model="mainForm.enginOrderNum" placeholder="请引用工程登录" disabled />
              <el-button style="margin-left: 10px" @click="openShareDetail">引用</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="mainForm.projectName" placeholder="请输入项目名称" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="行业类别" prop="loginType">
            <el-input v-model="mainForm.tradeCategory" placeholder="请输入行业类别" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="跨区厂编号" prop="factoryNo">
            <el-input v-model="mainForm.factoryNo" placeholder="请输入跨区厂编号" :disabled="isDealer" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="使用单位" prop="useUnit">
            <el-input v-model="mainForm.useUnit" placeholder="请输入使用单位" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程编号" prop="projectNo">
            <el-input v-model="mainForm.projectNo" placeholder="请输入工程编号" disabled />
          </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="请输入联系人" disabled />
          </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="请输入固定电话" disabled />
          </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="请输入移动电话" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="工程登录类型" prop="signType">
            <el-input v-model="mainForm.signType" placeholder="请输入工程登录类型" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="安装地址" prop="installAddress">
            <el-input v-model="mainForm.installAddress" placeholder="请输入安装地址" disabled />
          </el-form-item>
        </el-col>
        <el-col v-if="!isDealer" :xs="24" :sm="24" :lg="16">
          <el-form-item label="格力内部备注" prop="geLiInerNote">
            <el-input v-model="mainForm.geLiInerNote" placeholder="请输入格力内部备注" />
          </el-form-item>
        </el-col>
        <el-col v-if="!isDealer" :xs="24" :sm="12" :lg="8">
          <el-form-item label="权限分类" prop="powerCategory">
            <el-select
              v-model="mainForm.powerCategory"
              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="geLiNote">
            <el-input
              v-model="mainForm.geLiNote"
              :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"
              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="fileNo">
            <el-input v-model="mainForm.fileNo" placeholder="请输入文件编号" />
          </el-form-item>
        </el-col>
        <el-col v-if="mainForm.examineRemark" :xs="24" :sm="24" :lg="24">
          <el-form-item label="审批说明" prop="examineRemark">
            <el-input v-model="mainForm.examineRemark" placeholder="请输入审批说明" disabled />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="计划单">
            <el-radio-group v-model="isPlanOrder">
              <el-radio label="true">计划单</el-radio>
              <el-radio label="false">非计划单</el-radio>
            </el-radio-group>
            <span style="color: #ff0000; margin-left: 20px">注：如需开直调单，请下计划单，不要下非计划单</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="main-title">
      <div class="title">货品信息</div>
      <div>
        <el-select
          v-model="warehouseValue"
          placeholder="请选择发货仓库"
          size="small"
          style="margin-right: 10px"
          :disabled="!flag"
          @change="setStock"
        >
          <el-option v-for="(item, index) in warehouseList" :key="index" :label="item.name" :value="item.id" />
        </el-select>
        <el-button type="primary" size="small" icon="el-icon-search" @click="checkStock">检查库存</el-button>
      </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"
        @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" label="序号" type="index" width="50" />
        <!--        <el-table-column align="center" label="引用记录" prop="useRefCount" min-width="160" show-overflow-tooltip></el-table-column>-->
        <el-table-column align="center" label="销售类型" prop="saleTypeName" min-width="160" show-overflow-tooltip />
        <el-table-column align="center" label="物料编码" prop="materialNumber" min-width="160" 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="300" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-if="listItem" v-model="scope.row.specification" size="small" />
            <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="hasOrderQty" min-width="80" show-overflow-tooltip />
        <el-table-column align="center" label="单价" prop="price" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input
              v-if="!isDealer"
              v-model="scope.row.price"
              size="small"
              type="number"
              @mousewheel.native.prevent
            />
            <div v-else>{{ scope.row.price }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="工程信息数量" prop="enginNum" min-width="120" show-overflow-tooltip />
        <el-table-column align="center" label="数量" prop="qty" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.qty" size="small" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="仓库状态" prop="status2" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <div>{{ status2Filter(scope.row) }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单金额" prop="dd" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.price * scope.row.qty }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="返利钱包" prop="customerWalletId2" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.customerWalletId2"
              placeholder="选择返利类型"
              size="small"
              clearable
              @change="changeFlWallet(scope.$index)"
            >
              <el-option
                v-for="item in scope.row.rebateWallets"
                :key="item.customerWalletId"
                :label="item.customerWalletName"
                :value="item.customerWalletId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="返利金额" prop="fl" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ (scope.row.price * scope.row.qty * (scope.row.rebateRate * 100)) / 100 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="格力折扣" prop="zk" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.qty * scope.row.discAmount }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="现金钱包" prop="customerWalletId" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.customerWalletId"
              placeholder="选择现金钱包"
              size="small"
              clearable
              @change="changeXjWallet(scope.$index)"
            >
              <el-option
                v-for="item in scope.row.wallets"
                :key="item.customerWalletId"
                :label="item.customerWalletName"
                :value="item.customerWalletId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实付金额" prop="sf" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{
              (scope.row.price * scope.row.qty * 100 -
                ((scope.row.price * scope.row.qty * (scope.row.rebateRate * 100)) / 100) * 100 -
                ((scope.row.qty * (scope.row.discAmount * 100)) / 100) * 100) /
              100
            }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否直调" prop="isDirectTransfer" min-width="100">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.isDirectTransfer" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="直调数量" prop="directTransferQty" min-width="100" />
        <el-table-column align="center" label="已发货数量" prop="hasSendQty" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" label="已退数量" prop="retiredQty" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" label="备注" prop="remark" min-width="160" 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="tax" min-width="100" show-overflow-tooltip />
        <el-table-column align="center" label="仓库" prop="correspondName" min-width="100" show-overflow-tooltip />

        <el-table-column align="center" label="业务员" prop="serviceId" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-select v-model="scope.row.serviceId" placeholder="选择业务员" disabled size="small" clearable>
              <el-option
                v-for="item in salesmanList"
                :key="item.adminUserId"
                :label="item.nickName"
                :value="item.adminUserId"
              />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="deleteItem(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-footer">
      <div class="footer">
        <!-- <el-button type="primary" @click="clickSubmitForm(1)">保 存</el-button> -->
        <el-button type="primary" @click="clickSubmitForm(2)">提交审核</el-button>
        <el-popconfirm title="确定关闭吗？" style="margin-left: 10px" @onConfirm="goBack">
          <el-button slot="reference">返回列表</el-button>
        </el-popconfirm>
      </div>
    </div>

    <!-- 工程登录列表 -->
    <el-dialog
      title="工程登录列表"
      append-to-body
      :visible.sync="isShowDialog"
      width="70%"
      :close-on-click-modal="false"
    >
      <el-form ref="screenForm" :model="screenForm" label-width="0" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item prop="enginNum">
              <el-input v-model="screenForm.enginNum" placeholder="工程信息单" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item prop="projectName">
              <el-input v-model="screenForm.projectName" placeholder="工程项目" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item prop="useUnit">
              <el-input v-model="screenForm.useUnit" placeholder="使用单位" />
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :lg="6" class="tr">
            <el-form-item label="">
              <el-button size="small" @click="resetScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="table" style="margin: 10px 0 20px">
        <el-table
          v-loading="dialogTable_listLoading"
          :data="dialogTable_dataList"
          element-loading-text="Loading"
          tooltip-effect="dark"
          style="width: 100%"
          max-height="270"
        >
          <el-table-column align="center" label="" width="100">
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="chooseItem(scope.row.enginInfoNo)">选择</el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="orderDate" label="工程登录日期" show-overflow-tooltip />
          <el-table-column align="center" prop="enginInfoNo" label="工程信息单" show-overflow-tooltip />
          <el-table-column align="center" prop="projectName" label="工程项目" show-overflow-tooltip />
          <el-table-column align="center" prop="useUnit" label="使用单位" show-overflow-tooltip />
        </el-table>
      </div>
      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            :current-page="dialogTable_currentPage"
            :page-size="dialogTable_pageSize"
            background
            layout="prev, pager, next"
            :total="dialogTable_listTotal"
            @current-change="dialogTableCurrentChange"
          />
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowDialog = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOrderDetail,
  getComLoginList,
  getComLoginDetail,
  getWarehouseList,
  addCom,
  editCom,
  submitCom,
  checkStock,
  getWalletList
} from '@/api/supply/engin'
import { getDictList, getTypeList, getSalesmanList, getDealerList } from '@/api/common'
import { findElem } from '@/utils/util'
import { mapGetters } from 'vuex'

let that
export default {
  name: 'CommerceForm',
  componentName: 'CommerceForm',
  filters: {
    status1Filter(val) {
      const STOCK_ORDER_START = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_START').dictValue
      const STOCK_ORDER_END = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_END').dictValue
      const STOCK_ORDER_HAVE_START = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_HAVE_START').dictValue
      const STOCK_ORDER_HAVE_END = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_HAVE_END').dictValue
      const STOCK_ORDER_ALL_NUM = that.stockList.find(o => o.dictCode == 'STOCK_ORDER_ALL_NUM').dictValue
      if (val === '' || val === null || val === undefined) return '未检查'
      else if (val <= 0) return '无货'
      else if (val > STOCK_ORDER_START && val <= STOCK_ORDER_END) return val
      else if (val >= STOCK_ORDER_HAVE_START && val <= STOCK_ORDER_HAVE_END) return '有货'
      else if (val > STOCK_ORDER_ALL_NUM) return '充足'
    }
  },
  props: ['listItem'],
  data() {
    return {
      editId: '',
      mainForm: {
        orderNum: '',
        orderDate: '',
        // type: '',
        jxsNum: '',
        jxsName: '',
        jxsId: '',
        enginOrderNum: '',
        projectName: '',
        projectType: '',
        projectNote: '',
        machineType: '',
        useUnit: '',
        installAddress: '',
        projectNo: '',
        factoryNo: '',
        signType: '',
        tradeCategory: '',
        linkman: '',
        phone: '',
        tel: '',
        declareNo: '',
        powerCategory: '',
        geLiNote: '',
        geLiInerNote: '',
        remark: '',
        createMan: '',
        createDate: '',
        fileNo: '',
        salesMan: '',

        examineRemark: ''
      },
      mainFormRules: {
        // orderDate: [{ required: true, message: '请选择单据日期', trigger: 'change' }],
        jxsNum: [{ required: true, message: '请输入经销商编码', trigger: 'blur' }],
        jxsName: [{ required: true, message: '请输入经销商名称', trigger: 'blur' }],
        enginOrderNum: [{ required: true, message: '请输入工程登录编号', trigger: 'blur' }],
        // projectName: [{ required: true, message: '请输入项目类别', trigger: 'blur' }],
        // tradeCategory: [{ required: true, message: '请输入行业类别', trigger: 'blur' }],
        useUnit: [{ required: true, message: '请输入使用单位', trigger: 'blur' }],
        // linkman: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        // tel: [{ required: true, message: '请输入固定电话', trigger: 'blur' }],
        // phone: [{ required: true, message: '请输入移动电话', trigger: 'blur' }],
        installAddress: [{ required: true, message: '请输入安装地址', trigger: 'blur' }],
        projectNo: [{ required: true, message: '请输入工程编号', trigger: 'blur' }]
      },
      // typeList: [],
      stockList: [],
      goodsList: [],
      powerList: [],
      multipleSelection: [],
      dealerList: [],

      isShowDialog: false, // 工程登录列表 - 弹窗
      screenForm: {
        enginNum: '',
        projectName: '',
        useUnit: ''
      },
      dialogTable_dataList: null, // 工程登录列表 - 列表数据
      dialogTable_listLoading: true, // 工程登录列表 - 列表加载loading
      dialogTable_currentPage: 1, // 工程登录列表 - 当前页码
      dialogTable_pageSize: 10, // 工程登录列表 - 每页数量
      dialogTable_listTotal: 0, // 工程登录列表 - 列表总数

      warehouseList: [],
      warehouseValue: '',
      flag: false,
      isFirst: false,
      salesmanList: [],
      isPlanOrder: ''
    }
  },

  computed: {
    ...mapGetters(['websitNumber']),
    isDealer() {
      return JSON.parse(localStorage.getItem('supply_user')).isCustomer
    },

    outSalesmanList() {
      const list = []
      if (this.goodsList && this.goodsList.length) {
        this.goodsList.forEach(item => {
          if (item.serviceId) {
            const hasItem = findElem(list, 'adminUserId', item.serviceId)
            if (hasItem < 0) {
              const obj = this.salesmanList.find(o => o.adminUserId == item.serviceId)
              if (obj) {
                list.push(obj)
              }
            }
          }
        })
        if (this.isFirst) {
          this.isFirst = false
        } else {
          // this.mainForm.salesMan = this.goodsList[0].serviceId;
        }
      }
      return list
    }
  },

  watch: {
    goodsList: {
      handler(newValue, oldValue) {
        newValue.forEach(item => {
          item.dd = (item.price || 0) * (item.qty || 0)
          item.zk = item.qty * item.discAmount
          item.sf =
            (item.price * item.qty * 100 -
              ((item.price * item.qty * (item.rebateRate * 100)) / 100) * 100 -
              ((item.qty * (item.discAmount * 100)) / 100) * 100) /
            100

          item.fl = (item.price * item.qty * (item.rebateRate * 100)) / 100
          item.sums1 = [
            'number',
            'directTransferQty',
            'qty',
            'hasOrderQty',
            'enginNum',
            'oldQty',
            'hasSendQty',
            'retiredQty',
            'zk'
          ]
          item.sums2 = ['totalAmount', 'dd', 'fl', 'sf', 'payAmount', 'price', 'payRebateAmount', 'discAmount']
        })

        if (this.goodsList && this.goodsList.length) {
          this.flag = true
          if (this.isFirst) {
            this.isFirst = false
          } else {
            // this.mainForm.salesMan = this.goodsList[0].serviceId;
          }
          return newValue
        } else {
          this.flag = false
          this.mainForm.salesMan = ''
        }
      },
      immediate: true,
      deep: true
    }
  },

  beforeCreate() {
    that = this
  },

  async created() {
    await this.getSalesmanList()
    this.getDictList()
    this.getWarehouseList()
    this.getDealerList()
    if (this.websitNumber === 'GZ') {
      this.isPlanOrder = 'false'
    } else if (this.websitNumber === 'FS') {
      this.isPlanOrder = 'true'
    }

    if (this.listItem) {
      this.isFirst = true
      this.editId = this.listItem.parentId
      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()
    }
  },

  methods: {
    // 返回列表
    goBack() {
      this.$emit('backListFormDetail')
    },
    setStock(id) {
      if (this.goodsList.length) {
        const item = this.warehouseList.find(e => e.id === id)
        this.goodsList.forEach(k => {
          this.$set(k, 'correspondName', item.name)
          this.$set(k, 'correspondId', item.id)
        })
      }
    },
    getDate() {
      var date = new Date()
      var seperator1 = '-'
      var year = date.getFullYear()
      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
    },

    // 获取产品大类列表
    getDictList() {
      getDictList({ sysDictEnum: 'STOCK_ORDER' }).then(res => {
        this.stockList = res.data
      })
      getDictList({ sysDictEnum: 'POWER_CATEGORY' }).then(res => {
        this.powerList = res.data
      })
    },

    // 获取仓库列表
    getWarehouseList() {
      getWarehouseList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.warehouseList = res.data.records
      })
    },

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

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

    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 = ''
      }
    },

    // 获取详情
    getDetail() {
      getOrderDetail({ id: this.editId }).then(res => {
        const data = res.data
        this.mainForm.orderNum = data.enginOrderId
        this.mainForm.orderDate = data.orderDate
        // this.mainForm.type = data.mainId;
        this.mainForm.jxsNum = data.customerNumber
        this.mainForm.jxsName = data.customerName
        this.mainForm.enginOrderNum = data.refEnginRecordNo
        this.mainForm.projectName = data.refProjectName
        this.mainForm.projectType = data.refProjectType
        this.mainForm.projectNote = data.refProjectNote
        this.mainForm.machineType = data.refMachineType
        this.mainForm.useUnit = data.refUseUnit
        this.mainForm.installAddress = data.refInstallAddress
        this.mainForm.projectNo = data.refProjectNo
        this.mainForm.factoryNo = data.refFactoryNo
        this.mainForm.signType = data.refPromiseStatus
        this.mainForm.tradeCategory = data.refTradeCategory
        this.mainForm.linkman = data.refLinkman
        this.mainForm.phone = data.refPhone
        this.mainForm.tel = data.refTel
        this.mainForm.geLiInerNote = data.geLiInerNote
        this.mainForm.geLiNote = data.geLiNote
        this.mainForm.remark = data.remark
        this.mainForm.createMan = data.createName
        this.mainForm.createDate = data.createTime
        this.mainForm.fileNo = data.fileNo
        this.mainForm.salesMan = data.serviceId
        this.mainForm.examineRemark = data.examineNote
        this.mainForm.powerCategory = data.refPowerCategory
        this.isPlanOrder = String(data.isPlanOrder)
        data.items.forEach(item => {
          item.status1 = ''
          item.status2 = ''
          item.rebateWallets = item.customerWalletList.filter(item => {
            return item.type === 'REBATE'
          })
          item.wallets = item.customerWalletList.filter(item => {
            return item.type === 'COMMONLY'
          })
        })
        this.goodsList = data.items
      })
    },

    // 工程登录列表 - 获取列表
    getComLoginList() {
      getComLoginList({
        pageNum: this.dialogTable_currentPage,
        pageSize: this.dialogTable_pageSize,
        enginInfoNo: this.screenForm.enginNum,
        projectName: this.screenForm.projectName,
        useUnit: this.screenForm.useUnit,
        examineStatus: 'OK',
        isClose: false,
        customerKeyWord: this.listItem ? this.listItem.customerNumber : this.mainForm.jxsNum
      }).then(res => {
        this.dialogTable_dataList = res.data.records
        this.dialogTable_listTotal = res.data.total
        this.dialogTable_listLoading = false
      })
    },

    // 工程登录列表 - 打开弹窗
    openShareDetail() {
      if (!this.mainForm.jxsNum) {
        this.$errorMsg('请先选择经销商')
        return
      }
      this.isFirst = true
      this.isShowDialog = true
      this.dialogTable_currentPage = 1
      this.screenForm.correspondName = ''
      this.screenForm.correspondId = ''
      this.warehouseValue = ''
      this.getComLoginList()
    },

    // 工程登录列表 - 更改列表当前页
    dialogTableCurrentChange(val) {
      this.dialogTable_currentPage = val
      this.getComLoginList()
    },

    // 提交筛选表单
    submitScreenForm() {
      this.dialogTable_currentPage = 1
      this.getComLoginList()
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields()
      this.dialogTable_currentPage = 1
      this.getComLoginList()
    },

    // 选择工程登录
    chooseItem(id) {
      getComLoginDetail({
        recordNo: id,
        enginOrderId: this.mainForm.orderNum,
        customerId: this.mainForm.jxsId
      }).then(res => {
        this.isShowDialog = false
        const data = res.data
        this.mainForm.enginOrderNum = data.enginInfoNo
        this.mainForm.projectName = data.projectName
        this.mainForm.projectType = data.projectType
        this.mainForm.projectNote = data.projectNote
        this.mainForm.projectNo = data.projectNo
        this.mainForm.machineType = data.machineType
        this.mainForm.useUnit = data.useUnit
        this.mainForm.tradeCategory = data.tradeCategory
        this.mainForm.signType = data.enginSignType
        this.mainForm.factoryNo = data.enginFactoryNo
        this.mainForm.linkman = data.linkman
        this.mainForm.tel = data.tel
        this.mainForm.phone = data.phone
        this.mainForm.installAddress = data.installAddress
        this.mainForm.salesMan = data.serviceId
        this.mainForm.powerCategory = data.powerCategory
        this.mainForm.remark = data.remark
        this.mainForm.geLiInerNote = data.geLiInerNote
        this.mainForm.geLiNote = data.geLiNote
        this.mainForm.fileNo = data.fileNo
        // this.isPlanOrder = String(data.isPlanOrder)
        if (!this.isDealer) {
          this.mainForm.jxsNum = data.customerNumber
          this.mainForm.jxsName = data.customerName
        }

        this.goodsList = data.items.map(item => {
          return {
            useRefCount: item.useRefCount,
            saleTypeId: item.saleTypeId,
            saleTypeCode: item.saleTypeCode,
            saleTypeName: item.saleTypeName,
            materialId: item.materialId,
            materialNumber: item.materialNumber,
            materialOldNumber: item.materialOldNumber,
            materialName: item.materialName,
            specification: item.specification,
            enginNum: item.qty,
            enginPrice: item.price,
            enginTotality: item.totalAmount,
            historyHasDeliverQty: item.hasDeliverQty,
            unit: item.unit,
            price: item.price,
            qty: item.qty - item.hasOrderQty,
            customerWalletId2: '',
            rebateRate: '',
            discAmount: '',
            customerWalletId: '',
            isDirectTransfer: false,
            directTransferQty: 0,
            retiredQty: 0,
            hasSendQty: 0,
            hasOrderQty: item.hasOrderQty,
            remark: item.remark,
            tax: item.taxRate,
            status1: '',
            status2: '',
            serviceId: '',
            serviceName: '',
            rebateWallets: item.customerWalletList.filter(item => {
              return item.type === 'REBATE'
            }),
            wallets: item.customerWalletList.filter(item => {
              return item.type === 'COMMONLY'
            })
          }
        })
        this.goodsList.forEach(item => {
          item.customerWalletId = item.wallets && item.wallets.length ? item.wallets[0].customerWalletId : ''
          item.serviceId = item.wallets && item.wallets.length ? item.wallets[0].serviceId : ''
          item.serviceName = item.wallets && item.wallets.length ? item.wallets[0].serviceName : ''
        })
      })
    },

    // 删除产品
    deleteItem(index) {
      this.goodsList.splice(index, 1)
    },

    // 修改返利钱包
    changeFlWallet(index) {
      if (this.goodsList[index].customerWalletId2) {
        const obj = this.goodsList[index].rebateWallets.find(
          o => o.customerWalletId == this.goodsList[index].customerWalletId2
        )
        this.goodsList[index].rebateRate = obj.rebateRate
        this.goodsList[index].customerWalletName2 = obj.customerWalletName
      } else {
        this.goodsList[index].rebateRate = ''
        this.goodsList[index].customerWalletName2 = ''
      }
    },

    // 修改现金钱包
    changeXjWallet(index) {
      if (this.goodsList[index].customerWalletId) {
        const obj = this.goodsList[index].wallets.find(
          o => o.customerWalletId == this.goodsList[index].customerWalletId
        )
        this.goodsList[index].customerWalletName = obj.customerWalletName
        this.goodsList[index].serviceId = obj.serviceId
        this.goodsList[index].serviceName = obj.serviceName
      } else {
        this.goodsList[index].customerWalletName = ''
        this.goodsList[index].serviceId = ''
        this.goodsList[index].serviceName = ''
      }
    },

    // 检查库存
    checkStock() {
      if (!this.warehouseValue) {
        return this.$errorMsg('请选择仓库')
      }
      if (!this.goodsList) {
        return this.$errorMsg('请添加货品')
      }
      const ids = []
      this.goodsList.forEach(item => {
        ids.push(item.materialId)
      })
      checkStock({
        correspondId: this.warehouseValue,
        materialId: ids.join(',')
      }).then(res => {
        if (res.data) {
          this.goodsList.forEach((item, index) => {
            item.status1 = res.data[index].allStockNum
            item.status2 = res.data[index].stockNum
          })
        }
      })
    },

    status2Filter(item) {
      if (item.status2 === '' || item.status2 === null || item.status2 === undefined) return '未检查'
      else if (item.status2 <= 0) return '无货'
      if (item.status2 <= 0) {
        return '无货'
      } else if (item.status2 >= 1 && item.status2 <= 30) {
        return item.status2
      } else if (item.status2 >= 31 && item.status2 <= 1000) {
        return '有货'
      } else {
        return '充足'
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 保存 / 提交审核
    clickSubmitForm(type) {
      this.$refs.mainForm.validate(valid => {
        if (valid) {
          if (this.goodsList.length < 1) {
            return this.$errorMsg('请添加产品')
          }
          if (this.multipleSelection.length < 1) {
            return this.$errorMsg('请选择产品')
          }

          for (let i = 0; i < this.multipleSelection.length; i++) {
            if (!this.multipleSelection[i].customerWalletId) {
              this.$errorMsg('请选择现金钱包')
              return
            }
            if (!Number(this.multipleSelection[i].qty)) {
              this.$errorMsg('不允许数量为0')
              return
            }
            if (this.multipleSelection[i].qty > this.multipleSelection[i].enginNum) {
              this.$errorMsg('数量不能大于工程信息数量')
              return
            }
            if (!this.multipleSelection[i].correspondId) {
              this.$errorMsg('请选择仓库')
              return
            }
          }

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

          goodsList.forEach(item => {
            delete item.rebateWallets
            delete item.wallets
          })

          const saleManItem = this.mainForm.salesMan
            ? this.salesmanList.find(o => o.adminUserId == this.mainForm.salesMan)
            : ''
          const params = {
            enginOrderId: this.mainForm.orderNum,
            // orderDate: this.mainForm.orderDate,
            // mainId: this.mainForm.type || '',
            refEnginRecordNo: this.mainForm.enginOrderNum || '',
            refProjectName: this.mainForm.projectName || '',
            refProjectType: this.mainForm.projectType || '',
            refProjectNote: this.mainForm.projectNote || '',
            refUseUnit: this.mainForm.useUnit || '',
            refInstallAddress: this.mainForm.installAddress || '',
            refProjectNo: this.mainForm.projectNo || '',
            refFactoryNo: this.mainForm.factoryNo || '',
            refPromiseStatus: this.mainForm.signType || '',
            refTradeCategory: this.mainForm.tradeCategory || '',
            refLinkman: this.mainForm.linkman || '',
            refPhone: this.mainForm.phone || '',
            refTel: this.mainForm.tel || '',
            refPowerCategory: this.mainForm.powerCategory,
            refMachineType: this.mainForm.machineType,
            geLiInerNote: this.mainForm.geLiInerNote || '',
            geLiNote: this.mainForm.geLiNote || '',
            remark: this.mainForm.remark || '',
            fileNo: this.mainForm.fileNo || '',
            serviceId: this.mainForm.salesMan,
            correspondId: goodsList[0].correspondId,
            correspondName: goodsList[0].correspondName,
            serviceName: saleManItem ? saleManItem.nickName : goodsList[0].serviceName,
            isPlanOrder: this.isPlanOrder,
            items: goodsList
          }
          if (type === 1) {
            if (this.listItem) {
              editCom(params).then(res => {
                this.$successMsg('编辑成功')
                this.goBack()
                
              })
            } else {
              params.customerNumber = this.mainForm.jxsNum
              params.customerName = this.mainForm.jxsName
              params.customerId = this.mainForm.jxsId
              addCom(params).then(res => {
                this.$successMsg('新增成功')
                this.goBack()
                
              })
            }
          } else if (type === 2) {
            params.customerNumber = this.mainForm.jxsNum
            params.customerName = this.mainForm.jxsName
            params.customerId = this.mainForm.jxsId
            submitCom(params).then(res => {
              this.$successMsg('提交审核成功')
              this.goBack()
              
            })
          }
        }
      })
    }
  }
}
</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;
  }
}

::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>
