<!--提单通知管理新增、编辑-->
<template>
  <dialog-edit :width="'600px'" :visible.sync="dialogVisible" :editModel="editModel" :form="newFormValue"
               :formRules="formRules"
               ref="dialogRef"
               :title="editModel === 'C' ? $t('ladingNoticeManage.editPageAdd') : $t('ladingNoticeManage.editPageHead')"
               :api="api" @onSaved="onSaved" :autoSave="false" :footerBtnShow="false">
    <dym-form :formValue.sync="newFormValue" :componentList="componentList" @selectChanged="selectChanged"></dym-form>
    <el-col :xs="24" :sm="24" :md="24" :lg="24">
      <!-- 预计提单规模 -->
      <el-form-item :label="$t('ladingNoticeManage.planLadingEndScale')" label-width="175px" prop="predictLadingAmount">
        <el-row>
          <el-col :xs="20" :sm="20" :md="20" :lg="20">
            <el-input v-model="newFormValue.predictLadingAmount" :placeholder="$t('ladingNoticeManage.planLadingEndScale')" size="medium" :disabled="showdisabled()"></el-input>
          </el-col>
          <el-col :xs="4" :sm="4" :md="4" :lg="4" class="center-div">
            <span>{{$t('ladingNoticeManage.WanYuan')}}</span>
          </el-col>
        </el-row>
      </el-form-item>
    </el-col>
    <template slot="footer">
      <auth-button size=""
                   :loading="saveLoading1"
                   type="primary"
                   :menuCode="menuCode"
                   perms="addAndSave"
                   :openPerms="true"
                   v-if="editModel === 'C'"
                   :label="$t('common.saveandadd')"
                   @click="onSavedAndAdd"></auth-button>
      <auth-button size=""
                   :loading="saveLoading2"
                   type="primary"
                   :menuCode="menuCode"
                   perms="save"
                   :openPerms="true"
                   :label="$t('common.save')"
                   @click="onSaved"></auth-button>
      <auth-button size=""
                   :menuCode="menuCode"
                   perms="cancel"
                   :openPerms="true"
                   :label="$t('common.cancel')"
                   @click="dialogVisible=false"></auth-button>
    </template>
  </dialog-edit>
</template>

<script>
import { DialogEdit, authButton, SelectDictionary, dymForm,
  SelectCoreEnterpriseCascade, SelectProductName, SelectFinancialInstitutionsCascade,
  SelectAssetsServiceCascade, SelectPrimitiveRightsHolderCascade, SelectPeriodsCascade } from 'newepoch-components'
import BasePage from '@/pages/baseEditPage'
import ladingNoticeManageApi from '@/api/shouji/ladingNoticeManageApi'
import componentsApi from '@/api/componentsApi'
import { regExp } from '@/validator/index'
export default {
  extends: new BasePage(),
  name: 'ladingNoticeManageEdit',
  components: {
    DialogEdit,
    SelectDictionary,
    SelectProductName,
    authButton,
    dymForm
  },
  props: {
    menuCode: {
      type: String,
      default: null
    }
  },
  computed: {
    api () {
      return ladingNoticeManageApi.ladingNoticeManageListApi
    }
  },
  data () {
    const labelWidth = '175px' // 整体搜索文字大小
    return {
      saveLoading1: false,
      saveLoading2: false,
      newFormValue: {},
      // 编辑首次不触发事件
      flag: false,
      componentList: [
        // 产品名称
        {
          value: 'projectId',
          disabled: false,
          componentName: SelectProductName,
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.productName,
          labelWidth: labelWidth,
          name: 'projectId',
          placeholder: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.selectproductName,
          cols: [24, 24, 24, 24],
          prop: 'projectId'
        },
        // 期数
        {
          value: 'specialPlanId',
          name: 'specialPlanId',
          disabled: false,
          componentName: SelectPeriodsCascade,
          queryName: 'projectId',
          queryValue: 'projectId',
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.specialPlanPeriods,
          labelWidth: labelWidth,
          placeholder: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.selectspecialPlanPeriods,
          cols: [24, 24, 24, 24],
          prop: 'specialPlanId'
        },
        // 核心企业
        {
          value: 'coreEnterpriseId',
          name: 'coreEnterpriseId',
          disabled: false,
          componentName: SelectCoreEnterpriseCascade,
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.coreEnterprise,
          labelWidth: labelWidth,
          queryName: ['projectId'],
          queryValue: ['projectId'],
          placeholder: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.selectcoreEnterprise,
          cols: [24, 24, 24, 24],
          prop: 'coreEnterpriseId'
        },
        // 计划管理人/再保理银行
        {
          value: 'planningManagerId',
          name: 'planningManagerId',
          disabled: false,
          componentName: SelectFinancialInstitutionsCascade,
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.planningManagerName,
          labelWidth: labelWidth,
          queryName: ['projectId'],
          queryValue: ['projectId'],
          placeholder: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.selectplanningManagerName,
          cols: [24, 24, 24, 24],
          prop: 'planningManagerId'
        },
        // 提单类型
        {
          value: 'ladingType',
          name: 'ladingType',
          disabled: false,
          componentName: 'SelectDictionary',
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.ladingType,
          labelWidth: labelWidth,
          placeholder: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.selectladingType,
          cols: [24, 24, 24, 24],
          dictTypeCode: 'ZD0100',
          prop: 'ladingType'
        },
        // 资产服务机构
        {
          value: 'assetServiceId',
          name: 'assetServiceId',
          disabled: false,
          componentName: SelectAssetsServiceCascade,
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.assetServiceOrgan,
          labelWidth: labelWidth,
          queryName: ['projectId'],
          queryValue: ['projectId'],
          placeholder: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.selectassetServiceOrgan,
          cols: [24, 24, 24, 24],
          prop: 'assetServiceId'
        },
        // 原始权益人
        {
          value: 'initialOwnersId',
          name: 'initialOwnersId',
          disabled: false,
          componentName: SelectPrimitiveRightsHolderCascade,
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.rightsHolder,
          labelWidth: labelWidth,
          queryName: ['projectId'],
          queryValue: ['projectId'],
          placeholder: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.selectrightsHolder,
          cols: [24, 24, 24, 24],
          prop: 'initialOwnersId'
        },
        // 预计截单时间
        {
          value: 'predictStopTime',
          disabled: false,
          valueFormat: 'timestamp',
          componentName: 'el-date-picker',
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.estimatedCutOffTime,
          labelWidth: labelWidth,
          pickerOptions: {
            // console.log(date, date.getTime(), new Date(new Date().toLocaleDateString()).getTime())
            disabledDate (date) {
              return date.getTime() < new Date(new Date().toLocaleDateString()).getTime()
            }
          },
          placeholder: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.selectEestimatedCutOffTime,
          cols: [24, 24, 24, 24],
          prop: 'predictStopTime'
        }
      ],
      formRules: {
        projectId: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.validprojectId,
          trigger: 'change'
        }],
        specialPlanId: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.validspecialPlanId,
          trigger: 'change'
        }],
        coreEnterpriseId: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.validcoreEnterpriseId,
          trigger: 'change'
        }],
        planningManagerId: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.validplanningManagerId,
          trigger: 'change'
        }],
        ladingType: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.validladingType,
          trigger: 'change'
        }],
        assetServiceId: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.validassetServiceId,
          trigger: 'change'
        }],
        initialOwnersId: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.validinitialOwnersId,
          trigger: 'change'
        }],
        predictLadingAmount: [{
          validator: this.accountCheck,
          trigger: 'change'
        }]
      }
    }
  },
  methods: {
    showdisabled () {
      var a = (this.editModel === 'E' && (!!this.newFormValue.accountsReceivable && this.newFormValue.accountsReceivable !== '0'))
      return a
    },
    accountCheck (rule, value, callback) {
      if (this.UtilJs.isEmpty(value) || regExp.predictLadingAmounts.test(value)) {
        callback()
      } else {
        callback(new Error('整数部分14，小数4位'))
      }
    },
    // 根据ID获取产品类别
    getTypeById (projectId) {
      if (projectId) {
        componentsApi.productenterprise.getclassify({ projectId: projectId }).then(res => {
          if (res.data && res.data.productType) {
            this.newFormValue.isAbs = res.data.productType
            if (res.data.productType === '1') {
              this.formRules.specialPlanId[0].required = true
              if (this.editModel !== 'E') {
                this.componentList[1].disabled = false
              }
            } else {
              this.formRules.specialPlanId[0].required = false
              this.componentList[1].disabled = true
            }
          }
        })
      }
    },
    // 选中之后
    selectChanged (index, name, row) {
      if (index.projectIdInfo) {
        // 项目名称
        this.newFormValue.projectName = index.projectIdInfo.projectName
      } else if (index.specialPlanIdInfo) {
        // 专项计划期数
        // this.newFormValue.specialPlanPeriods = index.specialPlanIdInfo.specialPlanPeriods
        this.$set(this.newFormValue, 'specialPlanId', index.specialPlanIdInfo.keyId)
        this.newFormValue.specialPlanPeriods = index.specialPlanIdInfo.specialPlanPeriods
      } else if (index.coreEnterpriseIdInfo) {
        // 核心企业
        this.newFormValue.coreEnterpriseName = index.coreEnterpriseIdInfo.enterpriseName
      } else if (index.planningManagerIdInfo) {
        // 计划管理人/再保理银行
        this.newFormValue.planningManagerName = index.planningManagerIdInfo.enterpriseName
      } else if (index.assetServiceIdInfo) {
        // 资产服务机构
        this.newFormValue.assetServiceName = index.assetServiceIdInfo.enterpriseName
      } else if (index.initialOwnersIdInfo) {
        // 原始权益人
        this.newFormValue.initialOwnersName = index.initialOwnersIdInfo.enterpriseName
      }
      if (Object.keys(index).some(it => it === 'projectIdInfo') && this.editModel === 'C') {
        this.clearInfoList()
        if (this.newFormValue.projectId) {
          this.getTypeById(this.newFormValue.projectId)
        } else {
          this.formRules.specialPlanId[0].required = true
          this.componentList[1].disabled = false
        }
      }
    },
    // 保存
    onSaved () {
      this.$refs.dialogRef.$refs['editForm'].validate(valid => {
        let postData = JSON.parse(JSON.stringify(this.newFormValue))
        if (valid) {
          this.saveLoading2 = true
          this.clearUn()
          // 新增
          if (this.editModel === 'C') {
            ladingNoticeManageApi.ladingNoticeManageListApi.create(postData).then(res => {
              if (res.success) {
                this.success(this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.InsertSuess)
                this.dialogVisible = false
                this.$emit('close')
              }
            }).finally(res => {
              this.saveLoading2 = false
            })
          } else {
            // 修改
            if (this.UtilJs.isEmpty(postData.predictLadingAmount)) {
              this.$set(postData, 'predictLadingAmount', '0')
            }
            if (postData.noticeStatus) {
              delete postData.noticeStatus
            }
            ladingNoticeManageApi.ladingNoticeManageListApi.getUpdateModify(postData).then(res => {
              if (res.success) {
                this.success(this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.ModifyFaile)
                this.dialogVisible = false
                this.$emit('close')
              }
            }).finally(res => {
              this.saveLoading2 = false
            })
          }
        } else {
          this.error(this.$i18n.messages[this.$i18n.locale].common.formrulesMessage)
        }
      })
    },
    // 保存新增
    onSavedAndAdd () {
      this.$refs.dialogRef.$refs['editForm'].validate(valid => {
        if (valid) {
          this.saveLoading1 = true
          this.clearUn()
          ladingNoticeManageApi.ladingNoticeManageListApi.create(this.newFormValue).then(res => {
            if (res.success) {
              this.newFormValue = {}
              this.success(this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.InsertSuess)
              this.$emit('close')
              this.$nextTick(() => {
                this.clearValidate()
              })
            }
          }).finally(res => {
            this.saveLoading1 = false
          })
        } else {
          this.error(this.$i18n.messages[this.$i18n.locale].common.formrulesMessage)
        }
      })
    },
    // 清除为undefi
    clearUn () {
      let key = Object.keys(this.newFormValue)
      key.forEach(it => {
        if (!this.newFormValue[it]) {
          delete !this.newFormValue[it]
        }
      })
    },
    clearValidate () {
      if (this.$refs.dialogRef && this.$refs.dialogRef.$refs.editForm) {
        this.$refs.dialogRef.$refs.editForm.clearValidate()
      }
    },
    clearInfoList () {
      this.$set(this.newFormValue, 'coreEnterpriseId', '')
      this.$set(this.newFormValue, 'planningManagerId', '')
      this.$set(this.newFormValue, 'assetServiceId', '')
      this.$set(this.newFormValue, 'specialPlanId', '')
      this.$set(this.newFormValue, 'initialOwnersId', '')
      delete this.newFormValue.coreEnterpriseId
      delete this.newFormValue.planningManagerId
      delete this.newFormValue.assetServiceId
      delete this.newFormValue.initialOwnersId
      delete this.newFormValue.specialPlanId
      this.$nextTick(() => {
        this.clearValidate()
      })
    }
  },
  watch: {
    dialogVisible (n, o) {
      if (!n) {
        this.flag = false
        this.newFormValue = {}
      } else {
        this.saveLoading2 = false
        this.saveLoading1 = false
        this.newFormValue = Object.assign({}, this.form)
        this.newFormValue.specialPlanId = this.newFormValue.specialPlanId === '0' ? '' : this.newFormValue.specialPlanId
        if (this.newFormValue.predictStopTime === -2209017600000 || this.newFormValue.predictStopTime === '1900-01-01') {
          this.newFormValue.predictStopTime = ''
        }
        if (!this.newFormValue.predictLadingAmount || this.newFormValue.predictLadingAmount === 0) this.$set(this.newFormValue, 'predictLadingAmount', '')
        if (this.editModel === 'E') {
          this.componentList.forEach((item, index) => {
            if ((!this.newFormValue.accountsReceivable || this.newFormValue.accountsReceivable === '0') && (index === 7)) {
              this.$set(item, 'disabled', false)
            } else if (!(index === 4)) {
              this.$set(item, 'disabled', true)
            }
          })
          this.getTypeById(this.newFormValue.projectId)
        } else {
          this.componentList.forEach((item) => {
            this.$set(item, 'disabled', false)
          })
        }
        this.clearValidate()
      }
    }
  }
}
</script>

<style scoped lang="scss">
  @import '~@/styles/sj/ladingNoticeManage/ladingNoticeManageEdit.scss';
</style>
