<template>
  <div>
    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
      <headerTitle title="基本信息"></headerTitle>
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item
            label="单据类型"
            prop="documentType"
            style="margin-bottom: 22px"
          >
            <dict-selection
              dict-name="单据类型"
              v-model="form.documentType"
              @change="handleDocumentType"
            ></dict-selection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="申请部门"
            prop="applyDeptId"
            style="margin-bottom: 22px"
          >
            <ele-tree-select
              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="8">
          <el-form-item
            label="申请人"
            prop="applyUserId"
            style="margin-bottom: 22px"
          >
            <personSelect
              ref="directorRef"
              v-model="form.applyUserId"
              @selfChange="changeUserInfo"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item label="收款名称" style="margin-bottom: 22px">
            <el-input
              v-model="form.collectionName"
              clearable
              @click.native="handleSelectContact"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="开户行" style="margin-bottom: 22px">
            <el-input v-model="form.bankAccount" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="账户" style="margin-bottom: 22px">
            <el-input v-model="form.bankName" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="12">
        <el-col :span="8">
          <el-row style="display: flex; flex-direction: column">
            <el-col :span="24">
              <el-form-item label="金额" style="margin-bottom: 22px">
                <el-input v-model="form.amount" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item prop="repliedFiles" label="附件">
                <fileMain v-model="form.files"></fileMain>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="16">
          <el-form-item label="备注" style="margin-bottom: 22px">
            <el-input
              :rows="4"
              v-model="form.remark"
              type="textarea"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <headerTitle title="关联信息"></headerTitle>
    <fee-related-info-table
      ref="feeRelatedInfoTable"
      @setTotalPrice="setTotalPrice"
      :documentType="form.documentType"
      v-if="form.link.length || dialogType == 'add'"
      :link.sync="form.link"
    ></fee-related-info-table>
    <!--选择客户/供应商-->
    <customer-list-dialog
      v-if="customerListDialogFlag"
      :customerListDialogFlag.sync="customerListDialogFlag"
      ref="customerListDialogRef"
      @changeParent="getCustomerData"
    ></customer-list-dialog>
  </div>
</template>
<script>
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import { listOrganizations } from '@/api/system/organization';
  import { mapGetters } from 'vuex';
  import fileUpload from '@/components/upload/fileUpload.vue';
  import {
    feeApplyUpdateAPI,
    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';
  import feeRelatedInfoTable from '@/views/bpm/handleTask/components/financialManage/components/feeRelatedInfoTable.vue';
  import customerListDialog from '@/views/bpm/handleTask/components/financialManage/components/customerListDialog.vue';
  import { contactDetail } from '@/api/bpm/components/saleManage/contact';
  // import fileMain from '@/components/addDoc/index.vue';

  export default {
    name: 'add-or-edit-dialog',
    components: {
      // fileMain,
      fileUpload,
      personSelect,
      feeRelatedInfoTable,
      customerListDialog
    },
    computed: {
      ...mapGetters(['user'])
    },
    props: {
      businessId: {
        default: ''
      },
      taskDefinitionKey: {
        default: ''
      }
    },
    data() {
      return {
        contractListDialogFlag: false,
        customerListDialogFlag: false,
        dialogType: '',
        title: '',
        form: {
          id: '',
          documentType: '',
          collectionName: '',
          collectionId: '',
          bankName: '',
          bankAccount: '',
          accountingSubjectId: '',
          accountingSubjectCode: '',
          accountingSubjectName: '',
          amount: undefined,
          applyDeptId: '',
          applyDeptName: '',
          applyUserId: '',
          applyUserName: '',
          feeTypeId: '',
          feeTypeName: '',
          feeTypeCode: '',
          files: [],
          remark: '',
          link: []
        },
        feeTypeList: [],
        accountingSubjectList: [],
        deptList: [],
        deptTreeList: [],
        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' },
          documentType: { required: true, message: '请选择', trigger: 'change' }
        }
      };
    },
    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);
        this.form.documentType = this.form.documentType + '';
      },
      //选择供应商
      handleSelectContact(row) {
        if (this.form.documentType != '3') return;
        this.customerListDialogFlag = true;
        let params = {
          id: '',
          assetTreeId: '19',
          classType: 2,
          titleName: '选择供应商'
        };
        this.$nextTick(() => {
          this.$refs.customerListDialogRef.init(params);
        });
      },
      //获取选择 供应商/客户 数据
      async getCustomerData(params) {
        let { bankList } = await contactDetail(params.id);
        this.form.bankName = bankList[0].bankName;
        this.form.collectionId = params.id;
        this.form.collectionName = params.name;
        this.form.bankAccount = bankList[0].accountNo;
        // this.setSelectData(params)
      },
      downloadFile(file) {
        getFile({ objectName: file.storePath }, file.name);
      },
      //获取分类管理中的数据
      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;
      },
      // 获取部门数据
      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;
      },
      handleDocumentType(val, oldVal) {
        this.$message.warning('单据类型发生变化，请重新选择业务类型');
        this.$refs.feeRelatedInfoTable.clearData();
      },
      setTotalPrice(val) {
        this.form.amount = val;
      },
      //
      getTableValue() {
        return new Promise((resolve) => {
          this.$refs.form.validate(async (valid) => {
            if (!valid) return this.$message.warning('有必填项未填，请检查');
            this.form.link =
              await this.$refs.feeRelatedInfoTable.getTableValidate();
            const API = feeApplyUpdateAPI;
            const id = await API(this.form);
            resolve(id);
          });
        });
      }
    }
  };
</script>
<style scoped lang="scss"></style>
