
<template>
  <dialog-edit :width="'1000px'" :labelWidth="'70px'" :openPerms="true" savePerms="btnCreateSave"
               :visible.sync="dialogVisible" :editModel="editModel" :footerBtnShow="true" :menuCode="menuCode"
               :autoSave="false" @onSaved="save" :loading="saveLoading" :saveLabel="$t('common.submit')"
               :form="newFormValue" :title="$t('documentSealingTaskManage.createPageHead')" :api="api">
    <div>
      <el-form :rules="formrules" ref="formName" :model="newFormValue">
        <!--文件选择-->
        <span class="font-class">{{$t('documentSealingTaskManage.fileSelect')}}</span>
        <el-divider/>
        <dym-form :componentList="fileSelect" :formValue="newFormValue" :formrules="formrules" @selectChanged="selectChanged"></dym-form>
        <el-form-item :label="$t('documentSealingTaskManage.uploadFile')" :label-width="'160px'" prop="fileName">
          <el-col :sm="18">
            <el-input :clearable="true" v-model="newFormValue['fileName']"
                      :disabled="true"></el-input>
          </el-col>
          <el-col :sm="6" class="content-center">
            <btn-upload :uploadApi="uploadApi" size="small"  type="primary" :menuCode="menuCode"
                        :fileType="'.pdf,.png,.jpg'" :fileSize="50"
                        :fileID="newFormValue.fileId" :classType="false" :openPerms="true" perms="btnUpload"
                        :title="$t('ladingManageList.replenishData')" @uploadSuccess="uploadSuccess"></btn-upload>
            <btn-download :classType="true" :size="'small'" :type="'primary'"
                          :menuCode="menuCode" perms="btnDownLoad"
                          :openPerms="true" :downloadButtonMsg="$t('common.downLoad')"
                          :fileID="newFormValue.fileId"></btn-download>
          </el-col>
        </el-form-item>
        <!--适用范围-->
        <span class="font-class">{{$t('documentSealingTaskManage.scopeApplication')}}</span>
        <el-divider/>
        <dym-form :componentList="scopeofApplication" :formValue="newFormValue" @selectChanged="applicationChanged"></dym-form>
        <!--盖章参与方-->
        <div v-if="gaiZhangFang.length > 0">
          <span class="font-class" >{{$t('documentSealingTaskManage.sealedParticipants')}}</span>
          <el-divider/>
          <div v-for="(item) in gaiZhangFang" :key="item.dictId">
            <el-form-item label-width="160px" :label="item.label" :prop="item.prop" class="dymForm">
              <el-col :sm="24">
                <component :is="item.componentName" v-model="newFormValue[item.prop]" :placeholder="item.placeholder"
                           :clearable="true" :filterable="true" @selectChanged="selectItem(arguments, item.prop)">
                </component>
              </el-col>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
  </dialog-edit>
</template>

<script>
import { dymForm, DialogEdit, btnDownload, btnUpload, authButton, SelectDictionary, SelectProductName, SelectCoreEnterprise, SelectSupplier,
  SelectCoreEnterpriseCascade, SelectFinancialInstitutionsCascade, SelectPeriodsCascade, SelectProjectCompanyName, SelectAssetsService } from 'newepoch-components'
import BasePage from '@/pages/baseEditPage'
import { UPLOAD_API } from '@/constant'
import authcenterApi from '@/api/authcenterApi'
import customizejobApi from '@/api/shourangAssetassignee/customizejobApi'
import SelectDataSource from '@/components/element/shourang/SelectDataSource'
import SelectFileName from '@/components/element/shourang/SelectFileName'
import * as format from '@/filters/index'

export default {
  extends: new BasePage(),
  name: 'documentSealingTaskManageCreate',
  components: {
    // documentSealingTaskManageSelect,
    SelectDataSource,
    dymForm,
    DialogEdit,
    btnDownload,
    btnUpload,
    authButton,
    SelectDictionary,
    SelectProductName,
    SelectCoreEnterpriseCascade,
    SelectFinancialInstitutionsCascade,
    SelectPeriodsCascade,
    SelectProjectCompanyName,
    SelectCoreEnterprise,
    SelectSupplier,
    SelectAssetsService
  },
  props: {
    menuCode: {
      type: String,
      default: null
    }
  },
  computed: {
    api () {
      return authcenterApi.tenant
    }
  },
  data () {
    return {
      participateList: [],
      formItem: {},
      gaiZhangFang: [],
      saveLoading: false,
      uploadApi: UPLOAD_API,
      newFormValue: {
        assetSources: [],
        headquartersId: '',
        projectCompanyId: '',
        supplierId: '',
        assetsServiceId: ''
      },
      columList: [
        // 供应商
        {
          label: '',
          prop: 'headquartersId',
          placeholder: this.$t('common.pleaseSelect'),
          index: 0,
          dictId: '1',
          componentName: SelectSupplier,
          show: false
        },
        // 供应商原始权益人(保理商)
        {
          label: '',
          prop: 'projectCompanyId',
          placeholder: this.$t('common.pleaseSelect'),
          index: 0,
          dictId: '3',
          componentName: SelectAssetsService,
          show: false
        },
        // 项目公司
        {
          label: '',
          prop: 'supplierId',
          placeholder: this.$t('common.pleaseSelect'),
          index: 0,
          dictId: '4',
          componentName: SelectProjectCompanyName,
          show: false
        },
        // 核心企业
        {
          label: '',
          prop: 'assetsServiceId',
          placeholder: this.$t('common.pleaseSelect'),
          index: 0,
          dictId: '5',
          componentName: SelectCoreEnterprise,
          show: false
        }
      ],
      fileSelect: [
        // 资料名称
        {
          value: 'assetCustomStampConfigId',
          label: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.materialName,
          clearable: true,
          labelWidth: '160px',
          cols: [24, 24, 24, 24],
          prop: 'assetCustomStampConfigId',
          name: 'customStampConfig',
          componentName: SelectFileName
        },
        // 盖章方
        {
          value: 'assetSources',
          label: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.stampParty,
          clearable: true,
          labelWidth: '160px',
          cols: [24, 24, 24, 24],
          prop: 'assetSources',
          componentName: SelectDictionary,
          dictTypeCode: 'SCRS0138',
          placeholder: '',
          multiple: true,
          collapseTags: false,
          disabled: true
        }
      ],
      formrules: {
        assetCustomStampConfigId: [
          {
            trigger: 'change',
            required: true,
            message: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.selectmaterialName
          }
        ],
        fileName: [
          {
            trigger: 'blur',
            required: true,
            message: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.documentMust
          }
        ],
        projectCompanyId: [
          {
            trigger: 'change',
            required: true,
            message: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.selectAssetService
          }
        ],
        headquartersId: [
          {
            trigger: 'change',
            required: true,
            message: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.selectsupplierName
          }
        ],
        supplierId: [
          {
            trigger: 'change',
            required: true,
            message: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.selectprojectCompanyName
          }
        ],
        assetsServiceId: [
          {
            trigger: 'change',
            required: true,
            message: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.pleaseCoreEnter
          }
        ]
      },
      scopeofApplication: [
        // 产品名称
        {
          value: 'projectId',
          label: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.productName,
          clearable: true,
          labelWidth: '160px',
          cols: [24, 24, 24, 24],
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          componentName: SelectProductName,
          name: 'product',
          filterable: true,
          prop: 'projectId'
        },
        // 核心企业
        {
          value: 'coreEnterpriseId',
          label: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.coreEnterprises,
          clearable: true,
          labelWidth: '160px',
          cols: [24, 24, 24, 24],
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          componentName: SelectCoreEnterpriseCascade,
          name: 'coreEnterprise',
          filterable: true,
          queryName: 'projectId',
          queryValue: 'projectId',
          prop: 'coreEnterpriseId'
        },
        // 计划管理人/再保理银行
        {
          value: 'planningManagerId',
          label: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.refactorBank,
          clearable: true,
          labelWidth: '160px',
          cols: [24, 24, 24, 24],
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          componentName: SelectFinancialInstitutionsCascade,
          name: 'planManager',
          filterable: true,
          queryName: 'projectId',
          queryValue: 'projectId',
          prop: 'planningManagerName'
        },
        // 期数
        {
          value: 'specialPlanId',
          label: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.periodsNum,
          clearable: true,
          labelWidth: '160px',
          cols: [24, 24, 24, 24],
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          componentName: SelectPeriodsCascade,
          name: 'period',
          filterable: true,
          queryName: 'projectId',
          queryValue: 'projectId',
          prop: 'specialPlanPeriods'
        },
        // 备注
        {
          value: 'remark',
          label: this.$i18n.messages[this.$i18n.locale].documentSealingTaskManage.Remarks,
          clearable: true,
          labelWidth: '160px',
          cols: [24, 24, 24, 24],
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          componentName: 'el-input',
          type: 'textarea',
          name: 'remark',
          maxlength: '60',
          autosize: { minRows: 3, maxRows: 5 },
          filterable: true,
          prop: 'remark'
        }
      ]
    }
  },
  methods: {
    selectItem (a, id) {
      console.log(a, id)
      if (a[0]) {
        switch (id) {
          // 供应商
          case 'headquartersId':
            this.participateList.forEach(it => {
              if (it.participant === '1') {
                it.enterpriseId = a[0]
                it.enterpriseName = a[2].enterpriseName
              }
            })
            break
          // 供应商原始权益人(保理商)
          case 'projectCompanyId':
            this.participateList.forEach(it => {
              if (it.participant === '3') {
                it.enterpriseId = a[0]
                it.enterpriseName = a[2].enterpriseName
              }
            })
            break
          // 项目公司
          case 'supplierId':
            this.participateList.forEach(it => {
              if (it.participant === '4') {
                it.enterpriseId = a[0]
                it.enterpriseName = a[2].enterpriseName
              }
            })
            break
          // 核心企业
          case 'assetsServiceId':
            this.participateList.forEach(it => {
              if (it.participant === '5') {
                it.enterpriseId = a[0]
                it.enterpriseName = a[2].enterpriseName
              }
            })
            break
        }
      }
    },
    // 排序
    sortDict (data, col) {
      data.sort((a, b) => {
        return a[col] - b[col]
      })
      return data
    },
    // 上传成功
    uploadSuccess (returnData, rowData, fileList) {
      this.$set(this.newFormValue, 'fileName', returnData.fileName)
      this.$set(this.newFormValue, 'fileId', returnData.fileID)
    },
    // 资料选择事件
    selectChanged (data) {
      let _this = this
      _this.participateList = []
      if (!_this.UtilJs.isEmpty(data.customStampConfigInfo)) {
        this.newFormValue.assetSources = []
        _this.columList.forEach(it => it.show === false)
        _this.$set(this.newFormValue, 'assetName', data.customStampConfigInfo.assetName)
        customizejobApi.participateApi.getParticipate({ assetCustomStampConfigId: data.customStampConfigInfo.keyId }).then(res => {
          let data = res.data
          if (data) {
            data = this.sortDict(data, 'stampOrder')
            data.forEach(it => {
              this.newFormValue.assetSources.push(it.participant)
            })
            this.gaiZhangFang = this.columList.filter(it => {
              return data.some(it1 => {
                if (it1.participant === it.dictId) {
                  it.show = true
                  it.label = format.formatDict(it.dictId, 'SCRS0138')
                  it.index = it1.stampOrder
                  _this.participateList.push({
                    enterpriseId: '',
                    enterpriseName: '',
                    participant: it1.participant
                  })
                  return true
                }
              })
            })
            this.gaiZhangFang = this.sortDict(this.gaiZhangFang, 'index')
            console.log(this.gaiZhangFang)
          }
        })
      }
    },
    applicationChanged (obj) {
      let _this = this
      if (!_this.UtilJs.isEmpty(obj.productInfo)) {
        _this.$set(_this.newFormValue, 'projectName', obj.productInfo.projectName)
        _this.$set(_this.newFormValue, 'coreEnterpriseId', '')
        _this.$set(_this.newFormValue, 'planningManagerId', '')
        _this.$set(_this.newFormValue, 'specialPlanId', '')
      }
      if (!_this.UtilJs.isEmpty(obj.coreEnterpriseInfo)) {
        _this.$set(_this.newFormValue, 'coreEnterpriseName', obj.coreEnterpriseInfo.enterpriseName)
      }
      if (!_this.UtilJs.isEmpty(obj.planManagerInfo)) {
        _this.$set(_this.newFormValue, 'planningManagerName', obj.planManagerInfo.enterpriseName)
      }
      if (!_this.UtilJs.isEmpty(obj.periodInfo)) {
        _this.$set(_this.newFormValue, 'specialPlanPeriods', obj.periodInfo.specialPlanPeriods)
      }
      if (_this.UtilJs.isEmpty(_this.newFormValue.projectId)) {
        _this.$set(_this.newFormValue, 'projectName', '')
        _this.$set(_this.newFormValue, 'coreEnterpriseId', '')
        _this.$set(_this.newFormValue, 'planningManagerId', '')
        _this.$set(_this.newFormValue, 'specialPlanId', '')
      }
      if (_this.UtilJs.isEmpty(_this.newFormValue.coreEnterpriseId)) {
        _this.$set(_this.newFormValue, 'coreEnterpriseName', '')
      }
      if (_this.UtilJs.isEmpty(_this.newFormValue.planningManagerId)) {
        _this.$set(_this.newFormValue, 'planningManagerName', '')
      }
      if (_this.UtilJs.isEmpty(_this.newFormValue.specialPlanId)) {
        _this.$set(_this.newFormValue, 'specialPlanPeriods', '')
      }
    },
    // 保存
    save () {
      this.$refs['formName'].validate((valid) => {
        if (valid) {
          this.newFormValue.taskSubmitUserId = this.$store.state.user.user.userId
          this.newFormValue.taskSubmitUserName = this.$store.state.user.user.userName
          this.newFormValue.participateList = this.participateList
          this.saveLoading = true
          customizejobApi.participateApi.postData(this.newFormValue).then(res => {
            if (res.data) {
              this.success(this.$i18n.messages[this.$i18n.locale].paymentConfirmationManage.saveSuccess)
              this.$emit('create-success')
              this.dialogVisible = false
            } else {
              this.error(this.$i18n.messages[this.$i18n.locale].paymentConfirmationManage.saveError)
            }
          }).finally(() => {
            this.saveLoading = false
          })
        } else {
          this.error(this.$i18n.messages[this.$i18n.locale].common.formrulesMessage)
        }
      })
    }
  },
  watch: {
    visible (val) {
      let _this = this
      if (val) {
        this.newFormValue = Object.assign({}, this.form)
        _this.$nextTick(() => {
          this.saveLoading = false
          _this.$refs['formName'].clearValidate()
        })
      } else {
        _this.gaiZhangFang = []
        _this.$refs['formName'].clearValidate()
      }
    }
  }
}
</script>

<style scoped lang="scss" src="@/styles/shourang/documentSealingTaskManage/documentSealingTaskManageCreate.scss">
</style>
