<template>
  <div>
    <el-form ref="form" :model="dialogForm">
      <div>
        <el-divider direction="vertical"></el-divider>
        <span>应收金额：</span>
        <span>{{ form.receivableTotalPrice }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>已收金额：</span>
        <span>{{ receivedTotalPrice }}</span>
        <el-divider direction="vertical"></el-divider>
        <span>未收金额：</span>
        <span>{{ unreceiveTotalPrice < 0 ? 0 : unreceiveTotalPrice }}</span>
      </div>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="dialogForm.detailList"
        :needPage="false"
        :minHeight="100"
        tool-class="ele-toolbar-form"
        cache-key="collectionDialogTable"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
            v-if="dialogType !== 'view'"
            :disabled="unreceiveTotalPrice <= 0"
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="handleAddInfo"
          >
            新增收款信息
          </el-button>
        </template>

        <template v-slot:action="{ row, $index }">
          <el-link
            v-if="
              dialogType == 'view' && !row.invoiceStatus && !form.invoiceCode
            "
            type="primary"
            :underline="false"
            @click="addInvoice(row)"
          >
            新增发票
          </el-link>
          <el-popconfirm
            class="ele-action"
            title="确定要删除此信息吗？"
            @confirm="handleDelInfo($index)"
            v-if="dialogType !== 'view' && !row.invoiceCode"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
        <template
          v-slot:receivedDate="{ row, $index }"
          v-if="dialogType !== 'view'"
        >
          <el-form-item
            :prop="'detailList.' + $index + '.receivedDate'"
            :rules="{
              required: true,
              message: '请选择',
              trigger: ['blur', 'change']
            }"
          >
            <el-date-picker
              style="width: 95%"
              v-model="row.receivedDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              :disabled="!!row.invoiceCode"
            >
            </el-date-picker>
          </el-form-item>
        </template>
        <template
          v-slot:receivedTotalPrice="{ row, $index }"
          v-if="dialogType !== 'view'"
        >
          <el-form-item
            :prop="'detailList.' + $index + '.receivedTotalPrice'"
            :rules="{
              required: true,
              message: '请输入',
              trigger: ['blur', 'change']
            }"
          >
            <el-input-number
              @change="(val, oldVal) => handlePrice(val, oldVal, row, $index)"
              v-model="row.receivedTotalPrice"
              :disabled="!!row.invoiceCode"
              :controls="false"
              :precision="2"
              :min="0.0"
            ></el-input-number>
          </el-form-item>
        </template>
        <template v-slot:files="{ row, $index }">
          <el-form-item :prop="'detailList.' + $index + '.files'">
            <fileMain
              v-model="row.files"
              :type="dialogType == 'view' || row.invoiceCode ? 'view' : 'add'"
            ></fileMain>
          </el-form-item>
        </template>

        <template v-slot:remark="{ row, $index }" v-if="dialogType !== 'view'">
          <el-form-item>
            <el-input
              v-model="row.remark"
              type="textarea"
              :disabled="!!row.invoiceCode"
            ></el-input>
          </el-form-item>
        </template>
        <template v-slot:columnRequired="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
        <!-- 开票信息 -->
        <template v-slot:invoiceCode="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="handleInvoiceDetail(row, 'view')"
          >
            {{ row.invoiceCode }}
          </el-link>
        </template>
      </ele-pro-table>
    </el-form>
    <add-or-edit-dialog
      :add-or-edit-dialog-flag.sync="addOrEditDialogFlag"
      ref="addOrEditDialogRef"
      v-if="addOrEditDialogFlag"
      @reload="reload"
    ></add-or-edit-dialog>
    <!--开票详情-->
    <invoice-detail-dialog
      ref="invoiceDetailDialogRef"
      v-if="invoiceDetailDialogFlag"
      :detailDialogFlag.sync="invoiceDetailDialogFlag"
    ></invoice-detail-dialog>
  </div>
</template>

<script>
  import { deepClone } from '@/utils';
  import fileMain from '@/components/addDoc/index.vue';
  import addOrEditDialog from '@/views/financialManage/invoiceManage/components/addOrEditDialog.vue';
  import invoiceDetailDialog from '@/views/financialManage/invoiceManage/components/detailDialog.vue';
  export default {
    name: 'relatedInfoTable',
    components: { fileMain, addOrEditDialog,invoiceDetailDialog },
    props: {
      form: {
        type: Object,
        default: () => {}
      },
      dialogType: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        editIndex: undefined, //当前修改数据的下标
        dialogForm: {
          detailList: []
        },
        receivedTotalPrice: 0,
        unreceiveTotalPrice: 0,
        oldVal: 0,
        MAXPrice: 0,
        addOrEditDialogFlag: false,
        invoiceDetailDialogFlag: false
      };
    },
    computed: {
      columns() {
        let list = [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            minWidth: 120,
            prop: 'code',
            label: '编码',
            align: 'center',
            show: this.dialogType == 'view',
            showOverflowTooltip: true
          },
          {
            prop: 'receivedDate',
            label: '收款时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120,
            slot: 'receivedDate',
            headerSlot: 'columnRequired'
          },
          {
            prop: 'receivedTotalPrice',
            label: '已收金额',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130,
            slot: 'receivedTotalPrice',
            headerSlot: 'columnRequired'
          },
          {
            minWidth: 120,
            prop: 'invoiceCode',
            label: '发票编码',
            slot: 'invoiceCode',
            align: 'center',
            showOverflowTooltip: true,
            show: !this.form.invoiceCode
          },
          {
            prop: 'files',
            label: '附件',
            align: 'center',
            slot: 'files',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'remark',
            label: '备注',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 130,
            slot: 'remark'
          },
          {
            columnKey: 'action',
            slot: 'action',
            label: '操作',
            resizable: false,
            width: 160,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ];
        // 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;
      },
      getMAXPrice() {
        return this.MAXPrice;
      }
    },
    mounted() {
      this.init();
    },
    methods: {
      init() {
        this.dialogForm = deepClone(this.form);
        this.unreceiveTotalPrice = Number(this.dialogForm.unreceiveTotalPrice);
        this.dialogForm.detailList.forEach((item) => {
          this.MAXPrice =
            this.unreceiveTotalPrice + (Number(item.receivedTotalPrice) || 0);
        });
        this.receivedTotalPrice = Number(this.dialogForm.receivedTotalPrice);
      },
      handleInvoiceDetail(row = {}, type) {
        this.invoiceDetailDialogFlag = true;
        this.$nextTick(() => {
          let params = {
            id: row.invoiceId
          };
          this.$refs.invoiceDetailDialogRef.init(params, type);
        });
      },
      //新增关联信息数据
      handleAddInfo() {
        this.dialogForm.detailList.push({
          id: '',
          receivableCode: this.dialogForm.code,
          receivableId: this.dialogForm.id,
          receivedDate: '',
          receivedTotalPrice: undefined,
          remark: ''
          //unreceiveTotalPrice: this.dialogForm.unreceiveTotalPrice
        });
      },
      reload() {
        this.$emit('invoiceChange', this.dialogForm.id);
      },
      addInvoice(row) {
        this.addOrEditDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.addOrEditDialogRef.createInvoice1(
            { row, form: this.dialogForm },
            1,
            5
          );
        });
      },
      handlePrice(val, oldVal, row, index) {
        // this.$set(this.dialogForm.detailList[index], 'unreceiveTotalPrice', this.MAXPrice)
        // this.dialogForm.unreceiveTotalPrice = this.form.receivableTotalPrice - this.dialogForm.detailList.reduce((num, row) => {
        //   num += (Number(row.receivedTotalPrice) || 0)
        //   return num
        // }, 0)
        this.MAXPrice = this.unreceiveTotalPrice + (Number(oldVal) || 0);
        this.setPrice();
      },
      setPrice() {
        this.$nextTick(() => {
          this.receivedTotalPrice = this.dialogForm.detailList.reduce(
            (num, row) => {
              num += Number(row.receivedTotalPrice) || 0;
              return num;
            },
            0
          );
          this.unreceiveTotalPrice =
            this.form.receivableTotalPrice - this.receivedTotalPrice;
        });
      },
      handleDelInfo(index) {
        let price = this.dialogForm.detailList[index].receivedTotalPrice;
        this.dialogForm.detailList.splice(index, 1);
        this.dialogForm.detailList.forEach((item) => {
          this.MAXPrice =
            this.unreceiveTotalPrice +
            (Number(price) || 0) +
            item.receivedTotalPrice;
        });
        this.setPrice();
      },
      //
      getTableValidate() {
        return new Promise((resolve, reject) => {
          if (this.dialogForm.detailList.length == 0)
            return this.$message.warning('请至少新增一条收款信息');
          this.$refs.form.validate((valid) => {
            if (!valid) return this.$message.warning('请填写完整信息');
            console.log(this.dialogForm.detailList);
            resolve(this.dialogForm.detailList);
          });
        });
      }
    }
  };
</script>

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

  ::v-deep.el-divider {
    margin: 10px;
    font-weight: bold;
  }
</style>
