<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="确定要删除此信息吗？"
            :disabled="form.datasource.length==1"
            @confirm="handleDelInfo($index)"
          >
            <template v-slot:reference>
              <el-link
                :disabled="form.datasource.length==1"
                type="danger"
                :underline="false"
                icon="el-icon-delete"
              >
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
        <template v-slot:financeCostType="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.financeCostType'"
                        :rules="{required:true,message:'请选择',trigger:['blur','change']}">
            <ele-tree-select
              clearable
              filterable
              :ref="'feeTypeTree'+$index"
              :data="feeTypeList"
              v-model="row.financeCostTypeName"
              valueKey="id"
              labelKey="name"
              placeholder="请选择"
              @change="(val)=>changeFeeTypeInfo(val,row,$index)"
              default-expand-all
            />
          </el-form-item>
        </template>
        <template v-slot:linkType="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.linkType'">
            <!--            <DictSelection clearable dictName="关联类型" v-model="row.linkType"-->
            <!--                           :disabled="dialogType==='view'"-->
            <!--                           @itemChange="(val)=>handleChangeFinLink(val,row,$index)"></DictSelection>-->
            <el-select v-model="row.linkType" @change="(val)=>handleChangeFinLink(val,row,$index)" clearable>
              <el-option v-for="item in getLinkTypeList" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-slot:linkName="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.linkName'">
            <el-input v-model="row.linkName" @click.native="(val)=>handleSelectData(val,row,$index)"
                      clearable></el-input>
          </el-form-item>
        </template>
        <template v-slot:amount="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item :prop="'datasource.'+$index+'.amount'"
                        :rules="{required:true,message:'请选择',trigger:['blur','change']}">
            <el-input-number style="width: 100%" :controls="false" :min="0" v-model="row.amount" @change="handleChangeAmount"
                             clearable></el-input-number>
          </el-form-item>
        </template>
        <template v-slot:files="{row,$index}">
          <el-form-item :prop="'datasource.'+$index+'.files'">
            <fileUpload
              v-if="dialogType!=='view'"
              v-model="row.files"
              module="main"
              :showLib="false"
              :limit="1"
            />
            <el-link
              v-else-if="row.files.length"
              v-for="item in row.files"
              type="primary"
              :underline="false"
              @click="downloadFile(item)">
              {{ item.name }}
            </el-link>
          </el-form-item>
        </template>
        <template v-slot:remark="{row,$index}" v-if="dialogType!=='view'">
          <el-form-item>
            <el-input type="textarea" v-model="row.remark" clearable></el-input>
          </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 "@/views/financialManage/components/contractListDialog.vue";
import customerListDialog from "@/views/financialManage/components/customerListDialog.vue";
import saleOrderListDialog from "@/views/saleManage/saleOrder/invoice/components/orderListDialog.vue";
import purchaseOrderListDialog from "@/views/purchasingManage/purchaseOrder/invoice/components/orderListDialog.vue";
import opportunityDialog from "@/views/financialManage/components/opportunityDialog.vue";
import accountStatementDialog from "@/views/financialManage/components/accountstatementDialog.vue";
import planDialog from "@/views/financialManage/components/planDialog.vue";
import {getTreeByPid} from "@/api/classifyManage";
import {mapGetters} from 'vuex'
import {getByCode} from "@/api/system/dictionary-data";
import fileUpload from "@/components/upload/fileUpload.vue";
import {getFile} from "@/api/system/file";

export default {
  name: "relatedInfoTable",
  components: {
    fileUpload,
    purchaseOrderListDialog,
    saleOrderListDialog,
    customerListDialog,
    contractListDialog,
    opportunityDialog,
    accountStatementDialog,
    planDialog,
  },
  props: {
    link: {
      type: Array,
      default: () => []
    },
    documentType: {
      type: [String,Number],
      default: ''
    },

    dialogType: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      editIndex: undefined,//当前修改数据的下标
      contractType: undefined,//选择关联类型为合同时区分销售合同和采购合同
      contractListDialogFlag: false,
      customerListDialogFlag: false,
      opportunityDialogFlag: false,
      accountStatementDialogFlag: false,
      planDialogFlag: false,
      accountType: 1,
      feeTypeList: [],
      fin_link_type: [],
      CBToDT: {
        1: [900, 120, 100, 1000],
        2: [900, 120, 100, 230, 250, 260, 290],
        3: [230, 250, 260, 290],
        4: [],
      },
      form: {
        datasource: []
      },

    }
  },
  computed: {
    columns() {
      let list = [
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'financeCostTypeName',
          label: '财务费用类型',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 180,
          slot: 'financeCostType',
          headerSlot: 'headerGLLXMC',
        },
        // {
        //   prop: 'YWFYLX',
        //   label: '业务费用类型',
        //   align: 'center',
        //   showOverflowTooltip: true,
        //   minWidth: 150,
        //   slot: 'YWFYLX',
        //   headerSlot: 'headerGLLXMC',
        // },
        {
          prop: 'linkTypeName',
          label: '关联业务类型',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'linkType',
        },
        {
          prop: 'linkName',
          label: '单据名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 130,
          slot: 'linkName',
        },
        {
          prop: 'amount',
          label: '金额',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'amount',
          headerSlot: 'headerGLLXMC',
        },
        {
          prop: 'files',
          label: '附件凭证',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'files',
        },
        {
          prop: 'remark',
          label: '备注',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          slot: 'remark',
        },
      ]
      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
    },
    getLinkTypeList() {
      if (this.documentType == 4 || !this.documentType || !this.CBToDT[this.documentType]) return this.fin_link_type
      let data = []
      this.CBToDT[this.documentType].forEach(item => {
        let find = this.fin_link_type.find(i => i.value == item) || {}
        find.value && data.push(find)
      })
      return data
    },
  },
  async mounted() {
    this.form.datasource = this.link
    await this.getClassifyList(25, 'feeTypeList')
    let {data} = await getByCode('fin_link_type')
    this.fin_link_type = data.map(item => {
      let values = Object.keys(item)
      return {
        value: values[0],
        label: item[values[0]]
      }
    })
  },
  methods: {
    //获取分类管理中的数据
    async getClassifyList(id, listName) {
      let res = await getTreeByPid(id)
      this[listName] = res.data
    },
    downloadFile(file) {
      getFile({objectName: file.storePath}, file.name);
    },
    //新增关联信息数据
    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
      // }
    },
    //获取费用类别选中数据
    changeFeeTypeInfo(val, row, index) {
      this.editIndex = index
      if (!val) {
        this.$set(this.form.datasource[this.editIndex], 'financeCostTypeName', '')
        this.$set(this.form.datasource[this.editIndex], 'financeCostType', '')
      }
      let data = this.$refs['feeTypeTree' + index]?.$refs?.tree?.getCurrentNode() || {}
      this.$set(this.form.datasource[this.editIndex], 'financeCostTypeName', data.name)
      this.$set(this.form.datasource[this.editIndex], 'financeCostType', data.code)
    },

    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)
    },
    clearData() {
      this.form.datasource.forEach((item, index) => {
        this.$set(this.form.datasource[index], 'linkId', '')
        this.$set(this.form.datasource[index], 'linkName', '')
        this.$set(this.form.datasource[index], 'linkCode', '')
        this.$set(this.form.datasource[index], 'linkTypeName', '')
        this.$set(this.form.datasource[index], 'linkType', '')
      })
    },
    handleChangeAmount(val, row) {
      let totalPrice = this.form.datasource.reduce((total, item) => {
        total+= item.amount
        return total
      },0)
      this.$emit('setTotalPrice', totalPrice)
    },
    //删除关联信息数据
    handleDelInfo(index) {
      this.form.datasource.splice(index, 1)
      this.handleChangeAmount()
    },
    //修改关联类型
    handleChangeFinLink(val, row, index) {
      this.editIndex = index
      this.setSelectData({
        id: '',
        name: '',
        code: ''
      })
      this.$nextTick(() => {
        this.$refs.form.clearValidate('datasource.' + index + '.linkName')
      })
      if (!val) return row.linkTypeName = ''
      row.linkTypeName = this.fin_link_type.find(item => item.value == val)?.label

      // 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) {
      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>
