<template>
  <div>
    <el-form ref="form" :model="form">

      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="form.datasource"
        :needPage="false"
        :toolkit="[]"
        :minHeight="100"
        tool-class="ele-toolbar-form"
        cache-key="eomContactPageTable"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            v-if="dialogType!=='view'"
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="handleAddInfo">
            新增关联信息
          </el-button>
        </template>

        <template v-slot:action="{row,$index}">
          <el-popconfirm
            class="ele-action"
            title="确定要删除此信息吗？"
            @confirm="handleDelInfo($index)"
          >
            <template v-slot:reference>
              <el-link
                type="danger"
                :underline="false"
                icon="el-icon-delete"
              >
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
        <template v-slot:linkType="{row,$index}">
          <el-form-item :prop="'datasource.'+$index+'.linkType'"
                        :rules="{required:true,message:'请选择关联类型',trigger:['blur','change']}">
            <DictSelection clearable dictName="关联类型" v-model="row.linkType"
                           :disabled="dialogType==='view'"
                           @itemChange="(val)=>handleChangeFinLink(val,row,$index)"></DictSelection>
          </el-form-item>
        </template>
        <template v-slot:linkName="{row,$index}" v-if="dialogType!=='view'">
          <!--         客户   -->
          <el-form-item v-if="row.linkType==100" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,message:'请选择客户',trigger:['blur','change']}">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
          <!--        商机   -->
          <el-form-item v-else-if="row.linkType==120" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,message:'请选择商机',trigger:['blur','change']}">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
          <!--        销售合同   -->
          <el-form-item v-else-if="row.linkType==130" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,message:'请选择销售合同',trigger:['blur','change']}">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
          <!--        销售订单   -->
          <el-form-item v-else-if="row.linkType==140" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,message:'请选择销售订单',trigger:['blur','change']}">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
          <!--        销售对账单   -->
          <el-form-item v-else-if="row.linkType==190" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,message:'请选择销售对账单',trigger:['blur','change']}">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
          <!--        供应商   -->
          <el-form-item v-else-if="row.linkType==210" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,message:'请选择供应商',trigger:['blur','change']}">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
          <!--        采购计划   -->
          <el-form-item v-else-if="row.linkType==230" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,message:'请选择采购计划',trigger:['blur','change']}">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
          <!--        采购合同   -->
          <el-form-item v-else-if="row.linkType==250" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,trigger:['blur','change']}">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
          <!--        采购订单   -->
          <el-form-item v-else-if="row.linkType==260" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,message:'请选择采购订单',trigger:['blur','change']}">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>

          <!--        采购对账单   -->
          <el-form-item v-else-if="row.linkType==290" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,message:'请选择采购对账单',trigger:['blur','change']}">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
          <!--        项目   -->
          <el-form-item v-else-if="row.linkType==900" :prop="'datasource.'+$index+'.linkName'"
                        :rules="{required:true,trigger:['blur','change']}">

          </el-form-item>


        </template>
        <template v-slot:headerGLLXMC="{column}">
          <span class="is-required">{{ column.label }}</span>
        </template>
      </ele-pro-table>
    </el-form>
    <!--选择客户/供应商-->
    <customer-list-dialog v-if="customerListDialogFlag" :customerListDialogFlag.sync="customerListDialogFlag"
                          ref="customerListDialogRef" @changeParent="getCustomerData"></customer-list-dialog>
    <!--选择合同-->
    <contract-list-dialog v-if="contractListDialogFlag" :contractListDialogFlag.sync="contractListDialogFlag"
                          ref="contractListDialogRef" @changeParent="getContractData"
                          :type="contractType"></contract-list-dialog>
    <!--选择销售订单-->
    <sale-order-list-dialog ref="saleOrderListDialogRef" @changeParent="getOrderData"></sale-order-list-dialog>
    <!--选择采购订单-->
    <purchase-order-list-dialog ref="purchaseOrderListDialogRef"
                                @changeParent="getOrderData"></purchase-order-list-dialog>
    <!--商机-->
    <opportunity-dialog ref="opportunityDialogRef" v-if="opportunityDialogFlag"
                        :opportunityDialogFlag.sync="opportunityDialogFlag"
                        @changeParent="getOpportunityData">
    </opportunity-dialog>
    <!--对账单-->
    <account-statement-dialog ref="accountStatementDialogRef"
                              v-if="accountStatementDialogFlag"
                              :accountType="accountType"
                              :accountstatement-dialog-flag.sync="accountStatementDialogFlag"
                              @changeParent="getAccountData">
    </account-statement-dialog>
    <!--采购计划    -->
    <plan-dialog v-if="planDialogFlag"
                 :plan-dialog-flag.sync="planDialogFlag"
                 ref="planDialogRef"
                 @changeParent="getPlanData">
    </plan-dialog>

  </div>
</template>


<script>

import contractListDialog from "./contractListDialog.vue";
import customerListDialog from "./customerListDialog.vue";
import saleOrderListDialog from "@/views/bpm/handleTask/components/saleOrder/invoice/orderListDialog.vue";
import purchaseOrderListDialog from "@/views/bpm/handleTask/components/purchaseOrder/invoice/orderListDialog.vue";
import opportunityDialog from "./opportunityDialog.vue";
import accountStatementDialog from "./accountstatementDialog.vue";
import planDialog from "./planDialog.vue";

export default {
  name: "relatedInfoTable",
  components: {
    purchaseOrderListDialog,
    saleOrderListDialog,
    customerListDialog,
    contractListDialog,
    opportunityDialog,
    accountStatementDialog,
    planDialog,
  },
  props: {
    link: {
      type: Array,
      default: () => []
    },
    dialogType: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      editIndex: undefined,//当前修改数据的下标
      contractType: undefined,//选择关联类型为合同时区分销售合同和采购合同
      contractListDialogFlag: false,
      customerListDialogFlag: false,
      opportunityDialogFlag: false,
      accountStatementDialogFlag: false,
      planDialogFlag: false,
      accountType: 1,
      form: {
        datasource: []
      },

    }
  },
  computed: {
    columns() {
      let list = [
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'linkType',
          label: '关联类型',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'linkType',
          headerSlot: 'headerGLLXMC',
        },
        {
          prop: 'linkName',
          label: '关联类型名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 130,
          slot: 'linkName',
          headerSlot: 'headerGLLXMC'
        },
      ]
      let action = [{
        columnKey: 'action',
        slot: 'action',
        label: '操作',
        resizable: false,
        width: 80,
        align: 'center',
        showOverflowTooltip: true,
        fixed: 'right'
      },]
      this.dialogType === 'view' ? list = [...list] : list = [...list, ...action]
      return list
    },
  },
  mounted() {
    this.form.datasource = this.link
  },
  methods: {
    //新增关联信息数据
    handleAddInfo() {
      this.form.datasource.push(
        {
          linkType: '',
          linkTypeName: '',
          linkId: '',
          linkName: '',
          linkCode: '',
        }
      )
    },
    //
    handleSelectData(val, row, index) {
      this.editIndex = index
      if (val.target.nodeName == 'I') {
        row.linkId = ''
        row.linkName = ''
        row.linkCode = ''
        return
      }
      switch (row.linkType) {
        case '100': //客户
          this.handleSelectContact(row);
          break;
        case '120': //商机
          this.getOpportunityList(row);
          break
        case '130': //销售合同
          this.contractType = 1
          this.handleSelectContract(row);
          break
        case '140': //销售订单
          this.handleSelectSaleOrder(row);
          break;
        case '190': //销售对账单
          this.accountType = 1
          this.handleSelectAccount(row);
          break;
        case '210': //供应商
          this.handleSelectContact(row);
          break
        case '230': //采购计划
          this.handleSelectPlan(row);
          break
        case '250': //采购合同
          this.contractType = 2
          this.handleSelectContract(row);
          break;
        case '260': //采购订单
          this.handleSelectPurchaseOrder(row);
          break;
        case '290': //采购对账单
          this.accountType = 2
          this.handleSelectAccount(row);
          break;
        case '900': //项目
          this.handleSelectPurchaseOrder(row);
          break;


      }


      // // 客户/供应商
      // if (['100', '210'].includes(row.linkType)) {
      //   this.handleSelectContact(row)
      // }else if(['130', '250'].includes(row.linkType)){
      //   handleSelectContract
      // }

    },
    setSelectData(val) {
      this.$set(this.form.datasource[this.editIndex], 'linkId', val.id)
      this.$set(this.form.datasource[this.editIndex], 'linkName', val.name)
      this.$set(this.form.datasource[this.editIndex], 'linkCode', val.code)
    },
    //新增关联信息数据
    handleDelInfo(index) {
      this.form.datasource.splice(index, 1)
    },
    //修改关联类型
    handleChangeFinLink(val, row, index) {
      this.editIndex = index

      this.setSelectData({
        id: '',
        name: '',
        code: ''
      })
      this.$nextTick(() => {
        this.$refs.form.clearValidate('datasource.' + index + '.linkName')
      })
      if (!val.dictValue) return row.linkTypeName = ''
      row.linkTypeName = val.dictValue || ''

      // if (val.dictCode == 3) {
      //   this.getOpportunityList()
      // }

    },

    //选择客户或者供应商
    handleSelectContact(row) {
      this.customerListDialogFlag = true
      let params = {
        id: row.contactId,
        assetTreeId: row.linkType == 210 ? '19' : '17',
        classType: row.linkType == 210 ? 2 : 1,
        titleName: row.linkType == 210 ? '选择供应商' : '选择客户',
      }
      this.$nextTick(() => {
        this.$refs.customerListDialogRef.init(params)
      })
    },
    //获取选择 供应商/客户 数据
    getCustomerData(params) {
      this.setSelectData(params)
    },
    //获取商机
    async getOpportunityList() {
      this.opportunityDialogFlag = true
    },
    //获取选择的商机数据
    getOpportunityData(params) {
      console.log(params);
      let row = {
        id: params.id,
        name: params.name,
        code: params.code
      }
      this.setSelectData(row)
    },
    //对账单
    async handleSelectAccount() {
      this.accountStatementDialogFlag = true
    },
    //获取选择的对账单数据
    getAccountData(params) {
      let row = {
        id: params.id,
        name: params.statementNo,
        code: params.statementNo
      }
      this.setSelectData(row)
    },
    //采购计划
    async handleSelectPlan() {
      this.planDialogFlag = true
    },
    //获取选择的采购计划数据
    getPlanData(params) {
      console.log(params);
      let row = {
        id: params.id,
        name: params.planName,
        code: params.planCode
      }
      this.setSelectData(row)
    },
    //选择人员数据
    changeUserInfo(val, info) {
      this.form.applyUserName = info.name;
    },
    //选择合同
    handleSelectContract(val) {
      this.contractListDialogFlag = true
      this.$nextTick(() => {
        this.$refs.contractListDialogRef.init()
      })
    },
    //获取合同数据
    getContractData(params) {
      let row = {
        id: params.id,
        name: params.contractName,
        code: params.contractNo
      }
      this.setSelectData(row)
    },
    //选择销售订单
    handleSelectSaleOrder(val) {
      this.$refs.saleOrderListDialogRef.open();
    },
    //选择采购订单
    handleSelectPurchaseOrder(val) {
      this.$refs.purchaseOrderListDialogRef.open();
    },
    //获取采购/销售订单数据
    getOrderData(params) {
      let row = {
        id: params.id,
        name: params.orderNo,
        code: params.orderNo
      }
      this.setSelectData(row)
    },
    getTableValidate() {
      return new Promise((resolve, reject) => {
        if (this.form.datasource.length == 0) return this.$message.warning('请填写关联信息')
        this.$refs.form.validate((valid) => {
          if (!valid) return this.$message.warning('请填写完整信息')
          resolve(this.form.datasource)
        })
      })
    },
  }
}
</script>


<style scoped lang="scss">
:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
