<template>
  <!-- 待选择付款确认书一览 -->
  <div>
    <dialog-edit ref="dialogEdit" :visible.sync="dialogVisible" :form="queryParas" :closeLabel="$t('common.cancel')" :autoSave="autoSave" :formRules="formRules" :saveLabel="$t('common.assign')" :editModel="editModel" :api="api" width="95%"
      :appendToBody="appendToBody" :title="$t('packageOperation.addTitle')" @onSaved="handleSubmit" :autoClose="true" @close="close" :loading="assetpkgmgrButtonLoading">
      <div class="assetpkgmgr-box">
        <!-- 搜索栏 -->
        <div style="margin-bottom:10px">
          <!-- <dym-form :formValue.sync="queryParas" searchPerms="search" @handleFilter="handleFilter" @clearParam="clearParam"
            resetPerms="reset" :componentList="componentList"></dym-form> -->
          <dym-form :formValue.sync="queryParas" :componentList="componentList"></dym-form>
          <div align="right">
            <auth-button icon="iconfont iconycchaxun" :size="'medium'" :label="$t('common.search')" @click="isSearch = true;$refs.dialogEdit.save()"
              type="primary"></auth-button>
            <auth-button icon="iconfont iconyczhongzhi" :size="'medium'" :label="$t('common.reset')" @click="clearParam"
              type="primary"></auth-button>
          </div>
        </div>
        <!-- 表格列表 -->
        <data-table :api="api2" :operateBtnLayout="operateBtnLayout" v-bind="{maxHeight:300}" selectable="false" :showSelection="true" :queryParas="queryParas"
          :sourceData.sync="modifyData" :toolMenuFlag="toolMenuFlag" :columns="modifyColumns" :showPage="showPage" loadList="getAssetpackageList"
          :loadCount.sync="loadCount" :menuFlag="menuFlag" :headTitle="$t('packageOperation.addTitle')"
          @selectRowChange="selectRowChange" :loadingFlag="loadingFlag" @getTableData="getTableData">
          <!-- 列表结果集 -->
          <template v-if="editModel !== 'V'" slot="paginationLeft">
            <div align="left">
              <div>{{$t('common.pagePromptOne') + modifyData.length + $t('common.pagePromptTwo') + modifyData.length + $t('common.pagePromptThree')}}</div>
            </div>
          </template>
        </data-table>
      </div>
    </dialog-edit>
  </div>
</template>

<script>
import BaseEdit from '@/pages/baseEditPage'
import * as format from '@/filters/index.js'
import {
  DialogEdit,
  DataTable,
  dymForm,
  authButton
} from 'newepoch-components'
import SelectProductName from '@/components/element/assetpkgmgr/SelectProductName'
import packageOperation from '@/api/assetpkgmgr/packageOperationApi.js' // 再保理资料准备api接口
import externalApi from '@/api/assetpkgmgr/externalApi.js' // 外部api接口
export default {
  extends: new BaseEdit(),
  name: 'packageOperationsAddPop',
  components: {
    DialogEdit,
    DataTable,
    authButton,
    dymForm
  },
  props: {
    autoSave: {
      type: [Boolean],
      default: true
    },
    current: {
      type: [Object],
      default () {
        return null
      }
    }
  },
  data () {
    return {
      showPage: false, // 是否分页
      isSearch: false, // 是否搜索
      appendToBody: true,
      toolMenuFlag: false,
      loadCount: 0,
      menuFlag: false,
      operateBtnLayout: '',
      loadingFlag: false, // 加载动画控件
      queryParas: {},
      selectRows: [], // 选中项
      modifyData: [], // 列表
      contactData: [],
      // 基本信息表单验证
      formRules: {
        projectId: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect + this.$i18n.messages[this.$i18n.locale].packageOperation.projectName,
          trigger: 'blur'
        }]
      },
      forms: {},
      componentList: [
        {
        // 产品名称
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.projectName,
          disabled: false,
          value: 'projectId',
          queryName: 'productType',
          queryValue: 'productType',
          prop: 'projectId',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          labelWidth: '110px',
          cols: [12, 12, 8],
          clearable: true,
          name: 'project',
          componentName: SelectProductName
        },
        {
        // 付款确认书编号
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.assetCode,
          disabled: false,
          value: 'assetCode',
          cols: [12, 12, 8],
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '110px',
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 供应商
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.suppliersName,
          disabled: false,
          value: 'creditor',
          cols: [12, 12, 8],
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '110px',
          clearable: true,
          componentName: 'el-input'
        }
      ],
      modifyColumns: [
        // 付款确认书编号
        {
          prop: 'assetCode',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.assetCode,
          width: '250px'
        },
        // 供应商
        {
          prop: 'creditor',
          headerAlign: 'center',
          showOverflowTooltip: true,
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.suppliersName,
          width: '250px'
        },
        // 核心企业
        {
          prop: 'coreEnterpriseName',
          showOverflowTooltip: true,
          headerAlign: 'center',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.coreEnterpriseName,
          width: '230px'
        },
        // 区域
        {
          prop: 'coreAreaName',
          showOverflowTooltip: true,
          headerAlign: 'center',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.district,
          width: '200px'
        },
        // 项目公司名称
        {
          prop: 'debtor',
          headerAlign: 'center',
          showOverflowTooltip: true,
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.enterpriseName,
          width: '230px'
        },
        // 合同编号
        {
          prop: 'basicContractCode',
          align: 'center',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.constractCode,
          width: '230px'
        },
        // 合同名称
        {
          prop: 'basicContractName',
          headerAlign: 'center',
          showOverflowTooltip: true,
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.constractName,
          width: '300px'
        },
        // 费率
        {
          prop: 'factoringRate',
          headerAlign: 'center',
          align: 'right',
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.rate,
          width: '100px'
        },
        {
          // 账款到期日
          prop: 'dueDate',
          align: 'center',
          width: '115px',
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.dueDate,
          format: (row) => {
            return format.formatDateTpcModify(row.dueDate)
          }
        },
        {
          // 应收账款金额（元）
          prop: 'factoringMoney',
          headerAlign: 'center',
          align: 'right',
          width: '171px',
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.totalPrice,
          format: (row) => {
            return format.thousandFilter(row.factoringMoney)
          }
        }
      ]
    }
  },
  computed: {
    // 创建新资产包
    api () {
      return packageOperation.add
    },
    api2 () {
      return externalApi.query
    }
  },
  methods: {
    // 关闭回调
    close () {
      // 显示此页面
      this.dialogVisible = false
      if (!this.UtilJs.isEmpty(this.current)) {
        this.$parent.isBack = true
        this.$parent.dialogVisible = true
      }
    },
    // 去重
    array_diff (a, b) {
      for (let i = 0; i < b.length; i++) {
        for (let j = 0; j < a.length; j++) {
          if (a[j].assetCode === b[i]) {
            a.splice(j, 1)
            j = j - 1
          }
        }
      }
      return a
    },
    // 重组表格列表
    getTableData (e) {
      this.isSearch = false
      if (this.current && this.current.list.length > 0) {
        // console.log(this.current.list)
        this.modifyData = this.array_diff(e, this.current.list)
        // this.modifyData = e
      }
    },
    // 清除表单
    clearParam () {
      this.queryParas = {
        businessProcessStatus: '3004' // 再保理资产状态为3004待打包
        // deleteFlag: 0, // 未删除
        // backStatus: 0 // 未退单
      }
      // 如果是编辑迁移来的，则产品名称不重置
      if (this.current && this.current.projectId) {
        this.queryParas.projectId = this.current.projectId
      }
    },
    // 选中行
    selectRowChange (selectRows) {
      this.selectRows = selectRows
    },
    // 提交回调
    handleSubmit (e) {
      // 提交表单
      if (!this.isSearch) {
        let selectRows = this.selectRows
        // 选中项是否属于该产品（防止查询过后重选产品）
        for (let index in selectRows) {
          if (selectRows[index].projectId !== this.queryParas.projectId) {
            this.warning(this.$t('sendLoanInfo.noProject'))
            return
          }
        }
        if (selectRows.length > 0) {
          if (this.editModel === 'C') {
            this.assetpkgmgrFullScreenLoading()
            this.assetpkgmgrButtonLoading = true
            let item = selectRows[0]
            e = {
              assetCode: Array.from(selectRows, ({ assetCode }) => assetCode), // 付款确认书编号
              projectId: this.queryParas.projectId, // 产品id
              projectName: item.projectName, // 产品名称
              dueDate: item.dueDate.toString(), // 账款到期日
              factoringMoneyTotal: Array.from(selectRows, ({ factoringMoney }) => factoringMoney).reduce((x, y) => x + y).toFixed(2), // 保理总金额
              factorBankId: item.planOrBankId, // 再保理银行编码
              coreEnterpriseId: item.coreEnterpriseId, // 核心企业编号
              coreEnterpriseName: item.coreEnterpriseName, // 核心企业名称
              factorBankName: item.planOrBankName, // 再保理银行名称
              initialOwnersId: item.initialOwnersId, // 原始权益人ID
              initialOwnersName: item.initialOwnersName, // 原始权益人名称
              operateTime: new Date().getTime().toString(), // 打包人时间
              operateUserId: this.$store.getters.userId // 打包人
            }
            // 获取最大打包笔数限制
            externalApi.productPeriod.getList({ projectId: this.queryParas.projectId }).then(res => {
              if (res.success) {
                let packLimit = res.data.length > 0 ? res.data[0].packLimit : '0'
                // 比较当前打包数和最大打包笔数
                if (selectRows.length > packLimit && packLimit !== '0') {
                  this.assetpkgmgrFullScreenLoading().close()
                  this.assetpkgmgrButtonLoading = false
                  this.warning(this.$t('packageOperation.packLimitPrompt') + packLimit)
                } else {
                  e.packLimit = packLimit
                  // 保存
                  this.$emit('onSaved', e)
                }
              }
            }).catch(res => {
              this.assetpkgmgrFullScreenLoading().close()
              this.assetpkgmgrButtonLoading = false
            })
          } else {
            this.$emit('onSaved', selectRows)
          }
        } else {
          this.warning(this.$t('common.selectOperateTip'))
        }
      // 获取列表
      } else {
        this.handleFilter()
      }
    }
  },
  watch: {
    visible (val) {
      if (val) {
        let $this = this
        $this.clearParam()
        $this.modifyData = []
        $this.isSearch = false
        // 如果是编辑迁移来的，则产品名称不重置
        if (this.current && this.current.projectId) {
          $this.queryParas.projectId = this.current.projectId
          // 使产品名称不可选
          $this.componentList[0].disabled = true
          // 使产品名称校验非必要
          $this.formRules.projectId[0].required = false
          // 请求列表
          $this.$nextTick(() => {
            $this.handleFilter()
          })
        }
      }
    }
  }
}
</script>

<style scoped>
  @import "~@/styles/assetpkgmgr/common.scss";
</style>
