<!-- 预收款新增/编辑弹窗 -->
<template>
  <ele-modal
    width="70%"
    :visible="visible"
    :maxable="true"
    :append-to-body="true"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    :title="isDetail ? '预收款详情' : isUpdate ? '修改预收款' : '新增预收款'"
    @update:visible="updateVisible"
  >
    <!-- <div class="switch_left" v-if="isDetail">
      <ul>
        <li
          v-for="item in tabOptions"
          :key="item.key"
          :class="{ active: activeComp == item.key }"
          @click="activeComp = item.key"
        >
          {{ item.name }}
        </li>
      </ul>
    </div> -->
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      v-show="activeComp == 'main'"
    >
      <!-- 基本信息 -->
      <headerTitle title="基本信息" size="16px"></headerTitle>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="预收日期:" prop="advanceDate">
            <el-date-picker
              v-model="form.advanceDate"
              type="date"
              placeholder="请选择"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              :disabled="isDetail"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预收金额:" prop="advanceTotalPrice">
            <el-input
              v-model="form.advanceTotalPrice"
              placeholder="请输入"
              :disabled="isDetail"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="会计科目:" prop="accountingSubjectId">
            <ele-tree-select
              clearable
              :disabled="isDetail"
              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 :gutter="20">
        <el-col :span="8">
          <el-form-item label="客户名称:" prop="contactName">
            <el-input
              clearable
              v-model="form.contactName"
              @click.native="$refs.parentRef.open()"
              placeholder="请选择"
              readonly
              :disabled="isDetail"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="来源类型:" prop="sourceType">
            <el-select
              v-model="form.sourceType"
              placeholder="请选择"
              style="width: 100%"
              :disabled="isDetail"
            >
              <el-option label="销售订单" :value="3"></el-option>
              <el-option label="合同" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="来源编码:" prop="sourceCode">
            <el-input
              clearable
              v-model="form.sourceCode"
              @click.native="openSource"
              placeholder="请选择"
              :disabled="isDetail"
              readonly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="款项类型:" prop="fundType">
            <DictSelection
              dictName="预收款款项类型"
              clearable
              v-model="form.fundType"
              :disabled="isDetail"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收款条件:" prop="collectionConditionName">
            <!-- <el-select
              v-model="form.collectionConditionId"
              placeholder="请选择"
              style="width: 100%"
              :disabled="isDetail"
            >
              <el-option
                v-for="item in collectionTermsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select> -->
            <el-input
              clearable
              v-model="form.collectionConditionName"
              @click.native="openReceiveTerms"
              placeholder="请选择"
              :disabled="isDetail"
              readonly
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="备注:" prop="remark">
            <el-input
              v-model="form.remark"
              placeholder="请输入"
              :disabled="isDetail"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="附件:" prop="files">
            <fileMain
              v-model="form.files"
              :type="isDetail ? 'view' : 'add'"
            ></fileMain>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 物品清单 -->
      <headerTitle
        title="物品清单"
        size="16px"
        style="margin-top: 20px"
      ></headerTitle>
      <inventoryTableDetails
        ref="inventoryTableDetailsRef"
        :isAllPrice="false"
        :showSummary="true"
        :isSelected="false"
        cacheKeyUrl="eos-advanceReceipt-inventoryTableDetails"
      ></inventoryTableDetails>
      <!-- 收款信息 -->
      <div style="margin-top: 20px" v-if="isDetail">
        <headerTitle title="收款信息"></headerTitle>
        <div style="margin: 10px 0; font-size: 14px; color: #606266">
          <span>预收金额：{{ form.advanceTotalPrice || 0 }} 元</span>
          <span style="margin-left: 20px"
            >已收金额：{{ receivedAmount }} 元</span
          >
          <span style="margin-left: 20px"
            >未收金额：{{ unreceivedAmount }} 元</span
          >
        </div>

        <ele-pro-table
          ref="table"
          :needPage="false"
          :columns="columns"
          :datasource="form.detailList"
          :toolkit="[]"
        >
          <template v-slot:files="{ row: r }">
            <fileMain v-model="r.files" type="view"></fileMain>
          </template>
        </ele-pro-table>
      </div>
    </el-form>

    <template v-slot:footer>
      <template v-if="isDetail">
        <el-button @click="updateVisible(false)">关闭</el-button>
      </template>
      <template v-else>
        <el-button type="primary" :loading="loading" @click="save(0)">
          保存
        </el-button>
        <el-button type="primary" :loading="loading" @click="save(1)">
          提交
        </el-button>
        <el-button @click="updateVisible(false)">取消</el-button>
      </template>
    </template>
    <parentList ref="parentRef" @changeParent="changeParent"></parentList>
    <contractListDialog
      ref="selectContractRef"
      @changeParent="changeContract"
      :isChange="true"
      :contactData="{
        id: form.contactId
      }"
    ></contractListDialog>
    <!--  销售订单  -->
    <saleOrderListDialog
      ref="saleOrderListDialogRef"
      :contactData="{
        id: form.contactId
      }"
      @changeParent="changeOrder"
    ></saleOrderListDialog>
    <!-- 收款条件 -->
    <receiveTermsDialog ref="receiveTermsDialogRef" conditionType="rules" @changeParent="changeReceiveTerms"></receiveTermsDialog>
    <bpmDetail
      v-if="activeComp === 'bpm' && form.processInstanceId"
      :id="form.processInstanceId"
    ></bpmDetail>
  </ele-modal>
</template>

<script>
  import headerTitle from '@/components/header-title';
  import inventoryTableDetails from '@/BIZComponents/inventoryTableDetails.vue';
  import bpmDetail from '@/views/bpm/processInstance/detail.vue';
  import { getDetail } from '@/api/contractManage/contractBook';
  import {
    addAdvanceReceipt,
    updateAdvanceReceipt,
    getAdvanceReceiptInfo,
    submit
  } from '@/api/financialManage/advanceReceipt';
  import { getTreeByPid } from '@/api/classifyManage';
  import parentList from '@/views/saleManage/contact/components/parentList.vue';
  import contractListDialog from '@/views/saleManage/saleOrder/components/contractListDialog.vue';
  import saleOrderListDialog from '@/views/saleManage/saleOrder/invoice/components/orderListDialog.vue'; //销售订单
  import { getSaleOrderDetail } from '@/api/saleManage/saleorder';
  import receiveTermsDialog from './receiveTermsDialog.vue';
  export default {
    components: {
      headerTitle,
      inventoryTableDetails,
      contractListDialog,
      saleOrderListDialog,
      parentList,
      bpmDetail,
      receiveTermsDialog
    },
    data() {
      return {
        activeComp: 'main',
        businessId: '',
        tabOptions: [
          { key: 'main', name: '预收款项' },
          { key: 'bpm', name: '流程详情' }
        ],
        columns: [
          {
            type: 'index',
            label: '序号',
            width: 55,
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'receivedDate',
            label: '收款时间',
            align: 'center',
            minWidth: 160,
          },
          {
            prop: 'receivedTotalPrice',
            label: '已收金额',
            align: 'center',
            minWidth: 140,
            slot: 'receivedTotalPrice'
          },
          {
            prop: 'paymentTypeName',
            label: '支付类型',
            align: 'center',
            minWidth: 140,
          },
          {
            prop: 'files',
            label: '附件',
            align: 'center',
            minWidth: 120,
            slot: 'files'
          },
          {
            prop: 'remark',
            label: '备注',
            align: 'center',
            minWidth: 140,
            slot: 'remark'
          }
        ],
        visible: false,
        loading: false,
        isUpdate: false,
        isDetail: false,
        customerOptions: [],
        sourceCodeOptions: [],
        collectionTermsOptions: [],
        accountingSubjectList: [],
        form: {
          id: null,
          code: '',
          advanceDate: '',
          advanceTotalPrice: '',
          accountingSubjectId: '1779719367139792005',
          accountingSubjectCode: '2203',
          accountingSubjectName: '预收账款',
          contactName: '',
          contactId: '',
          sourceType: 3,
          sourceCode: '',
          fundType: 1,
          collectionConditionId: '',
          collectionConditionName: '',
          remark: '',
          files: [],
          detailList: []
        },
        rules: {
          advanceDate: [
            { required: true, message: '请选择预收日期', trigger: 'change' }
          ],
          advanceTotalPrice: [
            { required: true, message: '请输入预收金额', trigger: 'blur' }
          ],
          accountingSubjectId: [
            { required: true, message: '请选择会计科目', trigger: 'change' }
          ],
          contactName: [
            { required: true, message: '请选择客户名称', trigger: 'change' }
          ],
          sourceType: [
            { required: true, message: '请选择来源类型', trigger: 'change' }
          ],
          sourceCode: [
            { required: true, message: '请选择来源编码', trigger: 'change' }
          ],
          fundType: [
            { required: true, message: '请选择款项类型', trigger: 'change' }
          ]
        }
      };
    },
    computed: {
      receivedAmount() {
        const list = this.form.detailList || [];
        return list
          .reduce((sum, item) => {
            const val = parseFloat(item.receivedTotalPrice);
            return sum + (isNaN(val) ? 0 : val);
          }, 0)
          .toFixed(2);
      },
      unreceivedAmount() {
        const total = parseFloat(this.form.advanceTotalPrice) || 0;
        const received = parseFloat(this.receivedAmount) || 0;
        return (total - received).toFixed(2);
      }
    },
    methods: {
      changeReceiveTerms(row, index) {
        console.log('changeReceiveTerms~~~', row)
        this.form.collectionConditionId = row.id;
        this.form.collectionConditionName = row.name;
        console.log('changeReceiveTerms!!!', this.form)
        this.$forceUpdate()
      },
      generateCode() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const random = String(Math.floor(Math.random() * 900) + 100);
        this.form.code = `YSK${year}${month}${day}${random}`;
      },

      async open(type, row) {
        this.visible = true;
        this.activeComp = 'main';
        await this.getClassifyList(24, 'accountingSubjectList');
        this.isUpdate = type === 'edit';
        this.isDetail = type === 'detail';
        if ((this.isUpdate || this.isDetail) && row) {
          this.form = await getAdvanceReceiptInfo(row.id);
          this.businessId = row.id;
          this.$nextTick(() => {
            this.$refs.inventoryTableDetailsRef &&
              this.$refs.inventoryTableDetailsRef.putTableValue(
                this.form || []
              );
          });
        } else {
          this.resetForm();
          // this.generateCode();
          this.$nextTick(() => {
            this.$refs.inventoryTableDetailsRef &&
              this.$refs.inventoryTableDetailsRef.putTableValue([]);
          });
          this.form.accountingSubjectId = '1779719367139792005';
          this.form.accountingSubjectCode = '2203';
          this.form.accountingSubjectName = '预收账款';
        }
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.clearValidate();
        });
      },
      changeSubjectInfo(val) {
        const { code, name } = this.$refs.treeSelect.getNodeByValue(val);
        this.form.accountingSubjectCode = code;
        this.form.accountingSubjectName = name;
      },
      //获取分类管理中的数据
      async getClassifyList(id, listName) {
        let res = await getTreeByPid(id);
        this[listName] = res.data;
      },
      async changeParent(obj) {
        this.form.contactName = obj.name;
        this.form.contactId = obj.id;
      },

      openSource() {
        if (!this.form.contactName) {
          this.$message.error('请选择客户');
          return;
        }
        if (!this.form.sourceType) {
          this.$message.error('请选择来源类型');
          return;
        }
        if (this.form.sourceType == 3) {
          this.$refs.saleOrderListDialogRef.open();
        } else {
          this.$refs.selectContractRef.open();
        }
      },
      
      openReceiveTerms() {
        this.$refs.receiveTermsDialogRef.open();
      },
      async changeOrder(row) {
        this.form.sourceCode = row.orderNo;
        this.form.sourceId = row.id;
        const { productList, receiptPaymentList, payAmount } =
          await getSaleOrderDetail(row.id);

        this.$refs.inventoryTableDetailsRef.putTableValue({ productList });
        this.form.advanceTotalPrice = payAmount;
      },
      async changeContract(row) {
        console.log(row, 'dadas');
        this.form.sourceCode = row.contractNumber;
        this.form.sourceId = row.id;
        const { productList, receiptPaymentList, contractVO } = await getDetail(
          row.id
        );

        this.$refs.inventoryTableDetailsRef.putTableValue({ productList });
        this.form.advanceTotalPrice = contractVO.discountTotalPrice;
      },
      resetForm() {
        this.form = {
          id: null,
          code: '',
          advanceDate: '',
          advanceTotalPrice: '',
          accountingSubjectId: '1779719367139792005',
          accountingSubjectCode: '2203',
          accountingSubjectName: '预收账款',
          contactName: '',
          contactId: '',
          sourceType: 3,
          sourceCode: '',
          sourceId: '',
          fundType: 1,
          collectionConditionId: '',
          collectionConditionName: '',
          remark: '',
          files: [],
          detailList: []
        };
      },

      save(type) {
        this.$refs.form.validate((valid) => {
          if (!valid) return;
          this.loading = true;

          const saveOrUpdate = this.isUpdate
            ? updateAdvanceReceipt
            : addAdvanceReceipt;
          saveOrUpdate(this.form)
            .then((res) => {
              this.loading = false;
              this.$message.success(this.isUpdate ? '修改成功' : '新增成功');
              if(type === 1) {
                this.sub(res);
              }
              this.$emit('done');
            })
            .catch(() => {
              this.loading = false;
            });
        });
      },

      async sub(res) {
        const data = await getAdvanceReceiptInfo(
          this.businessId || res
        );
        submit(data.id).then(() => {
          this.$message.success('提交成功');
        })
      },

      updateVisible(value) {
        this.visible = value;
        if (!value) {
          this.resetForm();
        }
      }
    }
  };
</script>
