<template>
  <!-- 资产包编辑和查看 -->
  <div>
    <dialog-edit width="95%" :visible.sync="dialogVisible" :form="form" :editModel="editModel" :closeLabel="editModel === 'V' ? $t('common.close') :$t('common.cancel')" :saveLabel="$t('common.assign')" :autoSave="false" @onSaved="handleSubmit" :api="api2" :appendToBody="appendToBody"
      :title="editModel === 'V' ? $t('common.view') : $t('common.edit')" :autoClose="true" @close="close" :loading="assetpkgmgrButtonLoading">
      <div class="assetpkgmgr-box">
        <!-- 基础信息 -->
        <el-row v-if="editModel === 'V'" type="flex" align="bottom">
          <el-col :xs="12" :sm="12" :md="12"
                    :lg="8" :xl="8">
        <el-form-item :label="$t('packageOperation.projectName')" prop="projectName" label-width="80px">
            <el-input type="text" v-model="queryParas.projectName" disabled></el-input>
        </el-form-item>
          </el-col>
        </el-row>
        <!-- 搜索栏 -->
        <div v-else class="filter-container">
          <search-form :formValue.sync="queryParas" searchPerms="search" @handleFilter="getList" @clearParam="clearParam" resetPerms="reset" :componentList="componentList" :isShowFoldBtn="false"></search-form>
        </div>
        <!-- 表格列表 -->
        <data-table :api="api2" v-bind="{maxHeight:300}" :operateBtnLayout="operateBtnLayout" :queryParas="queryParas" :sourceData="modifyData"
          :toolMenuFlag="toolMenuFlag" :columns="modifyColumns" :showPage="showPage" :loadingFlag="loadingFlag" :loadCount.sync="loadCount" :menuFlag="menuFlag" :headTitle="$t('packageOperation.addTitle')" :showSelection="editModel === 'E'" @selectRowChange="selectRowChange">
          <!-- 头部操作栏 -->
          <template slot="headButton" v-if="editModel === 'E'">
            <div align="right">
              <auth-button class="iconfont iconxinzeng" :title="$t('common.create')" :label="$t('common.create')" type="primary" size="medium" @click="isAdd = true;dialogVisible=false"></auth-button>
              <auth-button class="iconfont iconshanchu" :title="$t('common.delete')" type="primary" :label="$t('common.delete')" size="medium" @click="deleteteItem"></auth-button>
            </div>
          </template>
          <!-- 列表结果集 -->
          <template 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>
    <!-- 新增 -->
    <package-operations-add-pop :visible.sync="isAdd" editModel="E" :form="form" :autoSave="false" @onSaved="addItem" :current="current"></package-operations-add-pop>
  </div>
</template>

<script>
import packageOperationsAddPop from './packageOperationsAddPop'
import BaseEdit from '@/pages/baseEditPage'
import * as format from '@/filters/index.js'
import {
  DialogEdit,
  DataTable,
  authButton,
  searchForm
} from 'newepoch-components'
import packageOperation from '@/api/assetpkgmgr/packageOperationApi.js'
import externalApi from '@/api/assetpkgmgr/externalApi.js'
export default {
  extends: new BaseEdit(),
  name: 'packageOperationsModPop',
  components: {
    DialogEdit,
    DataTable,
    authButton,
    packageOperationsAddPop,
    searchForm
  },
  data () {
    return {
      isBack: false, // 是否从新增回来
      isAdd: false, // 新增弹窗控件
      showPage: false,
      appendToBody: true,
      toolMenuFlag: true,
      loadCount: 0,
      menuFlag: false,
      loadingFlag: false, // 加载动画控件
      operateBtnLayout: '',
      queryParas: {
        keyId: ''
      },
      addList: [], // 添加列表
      modifyData: [],
      contactData: [],
      selectRows: [],
      componentList: [
        {
        // 产品名称
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.projectName,
          disabled: true,
          value: 'projectName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '120px',
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 付款确认书编号
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.assetCode,
          disabled: false,
          value: 'assetCode',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '120px',
          clearable: true,
          componentName: 'el-input'
        },
        {
        // 供应商
          label: this.$i18n.messages[this.$i18n.locale].packageOperation.suppliersName,
          disabled: false,
          value: 'creditor',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          labelWidth: '120px',
          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: '200px'
        },
        // 区域
        {
          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: '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)
          }
        }
      ],
      projectName: '',
      projectId: '',
      submitData: [], // 初始列表
      isFirst: true
    }
  },
  computed: {
    // 接口地址
    api2 () {
      return packageOperation.detail
    },
    // 传递给新增的参数
    current () {
      let list = this.modifyData.filter(item => {
        return !item.keyId
      }).map(item => {
        return item.assetCode
      })
      let current = {
        list: list,
        projectId: this.projectId
      }
      return current
    }
  },
  methods: {
    // 关闭窗口回调
    close () {
      this.isBack = false
      this.dialogVisible = false
    },
    // 重置表单
    clearParam () {
      let $this = this
      $this.queryParas = {
        keyId: $this.currentRow.keyId,
        projectName: $this.projectName
      }
    },
    // 提交保存
    handleSubmit () {
      let that = this
      if (that.addList.length > 0) {
      // 验证资产包是否为空
        if (that.modifyData.length > 0) {
          this.assetpkgmgrFullScreenLoading()
          this.assetpkgmgrButtonLoading = true
          // 获取最大打包笔数限制
          externalApi.productPeriod.getList({ projectId: that.projectId }).then(res => {
            if (res.success) {
              let packLimit = res.data.length > 0 ? res.data[0].packLimit : '0'
              // 比较当前打包数和最大打包笔数
              if (that.modifyData.length > packLimit && packLimit !== '0') {
                this.assetpkgmgrFullScreenLoading().close()
                this.assetpkgmgrButtonLoading = false
                that.warning(that.$t('packageOperation.packLimitPrompt') + packLimit)
              } else {
              // e.packLimit = packLimit
                let params = {
                  code: that.addList,
                  // factoringMoneyTotal: Array.from(that.modifyData, ({ factoringMoney }) => factoringMoney).reduce((x, y) => x + y).toFixed(2), // 保理总金额
                  assetPackageCode: that.currentRow.assetPackageCode
                }
                // 保存
                packageOperation.packageOperation.updatepackage(params).then(res => {
                  this.assetpkgmgrFullScreenLoading().close()
                  this.assetpkgmgrButtonLoading = false
                  if (res.success) {
                    that.success(that.$t('common.updateSuccess'))
                    that.close()
                    // 刷新主页面当前页
                    that.$parent.$refs.dataTable.loadTableData()
                  } else {
                    that.error(res.message)
                  }
                }).catch(res => {
                  this.assetpkgmgrFullScreenLoading().close()
                  this.assetpkgmgrButtonLoading = false
                })
              }
            } else {
              that.error(res.message)
            }
          }).catch(res => {
            this.assetpkgmgrFullScreenLoading().close()
            this.assetpkgmgrButtonLoading = false
          })
        } else {
        // 删除资产包
          that.assetpkgDel()
        }
      } else {
        that.close()
      }
    },
    // 删除资产包
    assetpkgDel () {
      let that = this
      // 确认提示框
      that.$confirm(that.$t('packageOperation.delSuccessful'), that.$t('common.tip'), {
        type: 'warning'
      }).then(() => {
        that.assetpkgmgrFullScreenLoading()
        packageOperation.packageOperation.deleteItem({ keyId: that.currentRow.keyId }).then(function (res) {
          that.assetpkgmgrFullScreenLoading().close()
          if (res.success) {
            // 重置表格
            that.$parent.$refs.dataTable.loadTableData()
            that.success(that.$t('common.delSuccess'))
            that.close()
          }
        }).catch((e) => {
          that.assetpkgmgrFullScreenLoading().close()
        })
      }).catch((e) => {})
    },
    // 选中行发生改变
    selectRowChange (selectRows, t) {
      this.selectRows = selectRows
    },
    // 添加行
    addItem (e) {
      let that = this
      that.isBack = true
      that.isAdd = false
      that.dialogVisible = true
      that.clearParam()
      that.modifyData = e.concat(that.modifyData)
      that.addList = that.addList.concat(Array.from(e, ({ assetCode }) => assetCode))
      that.$nextTick(() => {
        setTimeout(() => {
          that.success(that.$t('common.addSuccess'))
        }, 500)
      })
    },
    // 去重
    array_diff (a, b) {
      for (var i = 0; i < b.length; i++) {
        for (var j = 0; j < a.length; j++) {
          if (a[j].assetCode === b[i].assetCode) {
            a.splice(j, 1)
            j = j - 1
          }
        }
      }
      return a
    },
    // 删除选中行
    deleteteItem () {
      let that = this
      let row = that.selectRows
      let list = []
      // 判断是否选中
      if (row.length > 0) {
        let relativeRow = row.filter(item => {
          return item.keyId
        })
        // 若删除项是全部则删除资产包
        if (relativeRow.length === that.submitData.length) {
          // console.log(row.length, this.submitData.length)
          that.assetpkgDel()
        } else {
          that.$confirm(that.$t('common.confirmTip'), that.$t('common.warningTip'), { type: 'warning' }).then(function (res) {
            let delIds = []
            for (let i in row) {
              let item = row[i]
              if (item.keyId) {
                delIds.push(item.keyId)
              } else {
                that.addList.splice(that.addList.indexOf(item.assetCode), 1)
              }
            }
            // 若删除选项是原有项
            if (delIds.length > 0) {
              that.assetpkgmgrFullScreenLoading()
              packageOperation.packageOperation.deleteAssetCode({ keyId: delIds }).then(res => {
                that.assetpkgmgrFullScreenLoading().close()
                if (res.success) {
                  that.success(that.$t('common.delSuccess'))
                  that.submitData = that.array_diff(that.submitData, row)
                  list = that.array_diff(that.modifyData, row)
                  // 刷新主页面更新再报理金额
                  that.$parent.$refs.dataTable.loadTableData()
                  if (list.length > 0) {
                    that.modifyData = list
                  } else {
                    that.clearParam()
                    that.getList()
                  }
                  // 刷新主页面当前页
                }
              }).catch(res => {
                that.assetpkgmgrFullScreenLoading().close()
              })
            // 若删除选项是新增项
            } else {
              list = that.array_diff(that.modifyData, row)
              that.success(that.$t('common.delSuccess'))
              if (list.length > 0) {
                that.modifyData = list
              } else {
                that.clearParam()
                that.getList()
              }
            }
          }).catch((e) => {})
        }
      } else {
        that.warning(that.$t('common.delSelectedTip'))
      }
    },
    getList () {
      let $this = this
      $this.loadingFlag = true
      packageOperation.detail.getList($this.queryParas).then(res => {
        $this.loadingFlag = false
        if (res.success) {
          let datas = res.data
          // 显示列表
          $this.modifyData = datas.packageInfoManageList
          if (this.isFirst) {
            // 提交列表
            $this.submitData = $this.UtilJs.cloneDeep(datas.packageInfoManageList)
            this.isFirst = false
          }
          // 表单赋值
          $this.queryParas.projectName = datas.projectName
          $this.queryParas.projectId = datas.projectId
          $this.projectName = datas.projectName
          $this.projectId = datas.projectId
        }
      }).catch(res => {
        $this.loadingFlag = false
      })
    }
  },
  props: {
    currentRow: {
      type: [Object],
      default () {
        return null
      }
    }
  },
  watch: {
    visible (val) {
      let $this = this
      if (val && !this.isBack) {
        // 初始化
        $this.modifyData = []
        $this.queryParas = {}
        $this.queryParas.keyId = $this.currentRow.keyId
        $this.queryParas.projectName = $this.currentRow.projectName
        $this.isFirst = true
        // 请求列表
        $this.getList()
      } else if (!val && !this.isBack) {
        // 重置添加列表
        $this.addList = []
      }
    }
  }
}
</script>

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