<template>
  <div>

    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
      <headerTitle title="基本信息"></headerTitle>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            label="申请部门"
            prop="applyDeptId"
            style="margin-bottom: 22px"
          >
            <ele-tree-select
              :disabled="!['starter'].includes(taskDefinitionKey)"
              clearable
              :data="deptTreeList"
              v-model="form.applyDeptId"
              valueKey="id"
              labelKey="name"
              placeholder="请选择"
              @change="changeDeptInfo"
              default-expand-all
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="申请人"
            prop="applyUserId"
            style="margin-bottom: 22px"
          >
            <personSelect
              :disabled="!['starter'].includes(taskDefinitionKey)"
              ref="directorRef"
              v-model="form.applyUserId"
              @selfChange="changeUserInfo"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            label="费用类型"
            prop="feeTypeId"
            style="margin-bottom: 22px"
          >
            <ele-tree-select
              :disabled="!['starter'].includes(taskDefinitionKey)"
              clearable
              filterable
              ref="feeTypeTree"
              :data="feeTypeList"
              v-model="form.feeTypeId"
              valueKey="id"
              labelKey="name"
              placeholder="请选择"
              @change="changeFeeTypeInfo"
              default-expand-all
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="金额"
            prop="amount"
            style="margin-bottom: 22px">
            <el-input-number  :disabled="!['starter'].includes(taskDefinitionKey)" v-model="form.amount" :precision="2" :controls="false" style="width: 100%"
                             :min="0"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item
            label="关联类型"
            style="margin-bottom: 22px">
            <DictSelection  :disabled="!['starter'].includes(taskDefinitionKey)" clearable dictName="关联类型" v-model="form.finLinkType"
                           @itemChange="handleChangeFinLink"></DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="['financeApprove'].includes(taskDefinitionKey)">
          <el-form-item
            label="会计科目"
            prop="accountingSubjectId"
            style="margin-bottom: 22px"
          >
            <ele-tree-select
              clearable
              filterable
              ref="treeSelect"
              :data="accountingSubjectList"
              v-model="form.accountingSubjectId"
              valueKey="id"
              labelKey="name"
              placeholder="请选择"
              @change="changeSubjectInfo"
              default-expand-all
            />
          </el-form-item>
        </el-col >

      </el-row>
      <el-row v-if="form.finLinkType==1">
        <el-col :span="12">
          <el-form-item
            label="客户名称"
            prop="contactName"
            style="margin-bottom: 22px">
            <el-input  :disabled="!['starter'].includes(taskDefinitionKey)" v-model="form.contactName" @click.native="handleSelectContact" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.finLinkType==2">
        <el-col :span="12">
          <el-form-item
            label="供应商名称"
            prop="contactName"
            style="margin-bottom: 22px">
            <el-input :disabled="!['starter'].includes(taskDefinitionKey)" v-model="form.contactName" @click.native="handleSelectContact" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.finLinkType==3">
        <el-col :span="12">
          <el-form-item
            label="商机名称"
            style="margin-bottom: 22px">
            <el-select
              v-model="form.opportunityId"
              :disabled="!['starter'].includes(taskDefinitionKey)"
              style="width: 100%"
              @change="handleSelectOpportunity">
              <el-option
                v-for="item in opportunityList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.finLinkType==4">
        <el-col :span="12">
          <el-form-item
            label="选择合同"
            style="margin-bottom: 22px">
            <el-input :disabled="!['starter'].includes(taskDefinitionKey)" v-model="form.contractName" @click.native="handleSelectContract" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.finLinkType==5">
      </el-row>
      <el-row v-if="form.finLinkType==6">
        <el-col :span="12">
          <el-form-item
            label="销售订单"
            style="margin-bottom: 22px">
            <el-input :disabled="!['starter'].includes(taskDefinitionKey)" v-model="form.saleOrderCode" @click.native="handleSelectSaleOrder" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="采购订单"
            style="margin-bottom: 22px">
            <el-input :disabled="!['starter'].includes(taskDefinitionKey)" v-model="form.purchaseOrderCode" @click.native="handleSelectPurchaseOrder" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row :gutter="12">
        <el-col :span="24">
          <el-form-item
            label="备注"
            style="margin-bottom: 22px">
            <el-input :disabled="!['starter'].includes(taskDefinitionKey)" v-model="form.remark" type="textarea" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item prop="repliedFiles" label="附件">
            <fileUpload
              v-if="['starter'].includes(taskDefinitionKey)"
              v-model="form.files"
              module="main"
              :showLib="false"
              :limit="10"
            />
            <template  v-else>
              <el-link

                v-if="form.files.length"
                v-for="item in form.files"
                type="primary"
                :underline="false"
                @click="downloadFile(item)">
                {{ item.name }}
              </el-link>
            </template>

          </el-form-item>
        </el-col>
      </el-row>


    </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"></contract-list-dialog>
    <!--选择销售订单-->
    <sale-order-list-dialog ref="saleOrderListDialogRef" @changeParent="getSaleOrderData"></sale-order-list-dialog>
    <!--选择采购订单-->
    <purchase-order-list-dialog ref="purchaseOrderListDialogRef"
                                @changeParent="getPurchaseOrderData"></purchase-order-list-dialog>
  </div>
</template>
<script>
import personSelect from "@/components/CommomSelect/person-select.vue";
import {listOrganizations} from "@/api/system/organization";
import {mapGetters} from "vuex";
import customerListDialog from "./customerListDialog.vue";
import contractListDialog from './contractListDialog.vue'
import saleOrderListDialog from "@/views/bpm/handleTask/components/saleOrder/invoice/orderListDialog.vue";
import purchaseOrderListDialog from "@/views/bpm/handleTask/components/purchaseOrder/invoice/orderListDialog.vue";
import fileUpload from "@/components/upload/fileUpload.vue";
import {
  feeApplyUpdateAPI,
  finFeeApplySubmit,
  getFeeApplyInfoAPI
} from "@/api/bpm/components/financialManage/fee-manage/fee-application";
import {getTreeByPid} from "@/api/classifyManage";
import {getTableList} from '@/api/bpm/components/saleManage/quotation';
import {getFile} from "@/api/system/file";

export default {
  name: "add-or-edit-dialog",
  components: {
    fileUpload,
    purchaseOrderListDialog,
    saleOrderListDialog,
    personSelect,
    customerListDialog,
    contractListDialog
  },
  computed: {
    ...mapGetters(['user'])
  },
  props: {
    businessId: {
      default: ''
    },
    taskDefinitionKey:{
      default: ''
    },
  },
  data() {
    return {
      contractListDialogFlag: false,
      customerListDialogFlag: false,
      dialogType: '',
      title: '',
      form: {
        accountingSubjectId: '',
        accountingSubjectName: "",
        amount: undefined,
        applyDeptId: '',
        applyDeptName: "",
        applyUserId: '',
        applyUserName: "",
        contactId: '',
        contactName: "",
        contractCode: "",
        contractId: '',
        contractName: "",
        finLinkType: '',
        finLinkTypeName: '',
        feeTypeId: '',
        feeTypeName: "",
        feeTypeCode: "",
        files: [],
        opportunityId: '',
        opportunityName: "",
        projectId: '',
        projectName: "",
        purchaseOrderCode: "",
        purchaseOrderId: '',
        remark: "",
        saleOrderCode: "",
        saleOrderId: ''
      },
      feeTypeList: [],
      accountingSubjectList: [],
      deptList: [],
      deptTreeList: [],
      opportunityList: [],
      rules: {
        applyDeptId: {required: true, message: '请选择', trigger: 'change'},
        applyUserId: {required: true, message: '请选择', trigger: 'change'},
        accountingSubjectId: {required: true, message: '请选择', trigger: 'change'},
        feeTypeId: {required: true, message: '请选择', trigger: 'change'},
        amount: {required: true, message: '请输入', trigger: 'blur'},
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    //初始化
    async init(row = {}, type) {
      await this.getClassifyList(25, 'feeTypeList')
      await this.getClassifyList(24, 'accountingSubjectList')
      await this.getDeptList()
      await this.getFeeApplyInfoInfo(this.businessId)
      this.$nextTick(async () => {
        await this.getUserList(this.form.applyDeptId);
      })
    },
    //获取详情
    async getFeeApplyInfoInfo(id) {
      this.form = await getFeeApplyInfoAPI(id)
    },
    downloadFile(file) {
      getFile({objectName: file.storePath}, file.name);
    },
    //修改关联类型
    handleChangeFinLink(val) {
      this.form = Object.assign(this.form, {
        accountingSubjectId: '',
        accountingSubjectName: "",
        contactId: '',
        contactName: "",
        contractCode: "",
        contractId: '',
        contractName: "",
        opportunityId: '',
        opportunityName: "",
        projectId: '',
        projectName: "",
        purchaseOrderCode: "",
        purchaseOrderId: '',
        saleOrderCode: "",
        saleOrderId: ''
      })
      if (!val.dictValue) return
      this.form.finLinkTypeName = val.dictValue || ''
      if (val.dictCode == 3) {
        this.getOpportunityList()
      }

    },
    //获取分类管理中的数据
    async getClassifyList(id, listName) {
      let res = await getTreeByPid(id)
      this[listName] = res.data
    },
    //获取费用类别选中数据
    changeFeeTypeInfo(val) {
      if (!val) {
        this.form.feeTypeName = ''
        this.form.feeTypeCode = ''
      }
      let data = this.$refs.feeTypeTree?.$refs?.tree?.getCurrentNode() || {}
      this.form.feeTypeName = data.name
      this.form.feeTypeCode = data.code
    },
    //获取会计科目选中数据
    changeSubjectInfo(val) {
      if (!val) return this.form.accountingSubjectName = ''
      let data = this.$refs.treeSelect?.$refs?.tree?.getCurrentNode() || {}
      this.form.accountingSubjectName = data.name
    },

    //选择客户或者供应商
    handleSelectContact(val) {
      if (val.target.nodeName == 'I') {
        this.form.contactId = ''
        this.form.contactName = ''
        this.form.opportunityId = ''
        this.form.opportunityName = ''
        this.opportunityList = []
        return
      }
      this.customerListDialogFlag = true
      let params = {
        id: this.form.contactId,
        assetTreeId: this.form.finLinkType == 2 ? '19' : '17',
        classType: this.form.finLinkType || 1,
        titleName: this.form.finLinkType == 2 ? '选择供应商' : '选择客户',
      }
      this.$nextTick(() => {
        this.$refs.customerListDialogRef.init(params)
      })
    },
    //获取选择 供应商/客户 数据
    getCustomerData(params) {
      this.form.contactId = params.id
      this.form.contactName = params.name
    },
    //获取客户的商机列表
    async getOpportunityList() {
      const data = await getTableList({
        pageNum: 1,
        size: 999,
        approvalStatus: 2
      });
      //  contactName: name,
      this.opportunityList = data.list;
    },
    //获取选择的商机数据
    handleSelectOpportunity(val) {
      if (!val) return this.form.opportunityName = ''
      this.form.opportunityName = this.opportunityList.find(item => item.id == val)?.name
    },
    // 获取部门数据
    getDeptList() {
      listOrganizations().then((list) => {
        this.deptList = list;
        this.deptTreeList = this.$util.toTreeData({
          data: list,
          idField: 'id',
          parentIdField: 'parentId'
        });
      });
    },
    // 选择负责人部门
    changeDeptInfo(id) {
      const info = this.deptList.find((e) => e.id == id) || {};
      this.form.applyDeptName = info.name;
      this.form.applyUserId = '';
      this.form.applyUserName = '';
      this.getUserList(id);
    },
    // 获取人员数据
    getUserList(deptId) {
      if (deptId) {
        this.$refs.directorRef.getList({deptId});
      }
    },
    //选择人员数据
    changeUserInfo(val, info) {
      this.form.applyUserName = info.name;
    },
    //选择合同
    handleSelectContract(val) {
      if (val.target.nodeName == 'I') {
        this.form.contractId = ''
        this.form.contractName = ''
        return
      }
      this.contractListDialogFlag = true
      this.$nextTick(() => {
        this.$refs.contractListDialogRef.init()
      })
    },
    //获取合同数据
    getContractData(params) {
      this.form.contractId = params.type == 1 ? params.partaId : params.partbName
      this.form.contractName = params.type == 1 ? params.partaName : params.partbName
    },
    //选择销售订单
    handleSelectSaleOrder(val) {
      if (val.target.nodeName == 'I') {
        this.form.saleOrderId = ''
        this.form.saleOrderCode = ''
        return
      }
      this.$refs.saleOrderListDialogRef.open();
    },
    //获取销售订单数据
    getSaleOrderData(obj) {
      this.form = Object.assign({}, this.form, {
        saleOrderId: obj.id,
        saleOrderCode: obj.orderNo
      });
    },
    //选择采购订单
    handleSelectPurchaseOrder(val) {
      if (val.target.nodeName == 'I') {
        this.form.purchaseOrderId = ''
        this.form.purchaseOrderCode = ''
        return
      }
      this.$refs.purchaseOrderListDialogRef.open();
    },
    //获取采购订单数据
    getPurchaseOrderData(obj) {
      this.form = Object.assign({}, this.form, {
        purchaseOrderId: obj.id,
        purchaseOrderCode: obj.orderNo
      });
    },

    //
    getTableValue() {
      return new Promise((resolve) => {
        this.$refs.form.validate(async valid => {
          if (!valid) return this.$message.warning('有必填项未填，请检查')
          const API = feeApplyUpdateAPI
          const id = await API(this.form)
          resolve(id)
        })
      })
    },
  }
}
</script>
<style scoped lang="scss">

</style>
