<template>
    <div>
        <dialog-edit v-if="dialogVisible"
                :visible.sync="dialogVisible"
                :title="$t('common.initiateTask')"
                editModel="E"
                :form="dialogForm"
                :api="dialogApi"
                :appendToBody="true"
                :footerBtnShow="false"
                :autoClose="true"
                @close="close">

            <!--任务类型-->
            <el-row class="marginBottom9">
                <el-tabs>
                    <el-tab-pane :label="(!openSatus?$t('common.select'):'')+$t('traceMgr.taskType')"></el-tab-pane>
                </el-tabs>

                <template>
                    <el-form>
                        <el-form-item :label="$t('traceMgr.taskType')+'：'">
                            <el-col :span="4" v-show="serviceTask">
                                <el-select v-model="taskTypeValue"
                                           :placeholder="$t('common.point')">
                                    <el-option
                                            v-for="item in taskTypeOptions"
                                            :key="item.dictId"
                                            :label="item.dictName"
                                            :value="item.dictId">
                                    </el-option>
                                </el-select>
                            </el-col>
                            <auth-button v-show="serviceTask" type="primary" size="medium" :label="$t('traceMgr.sure')"
                                         @click="taskTypeConfirm"></auth-button>
                            <el-col :span="4" v-show="!serviceTask">
                                <span>{{$t('traceMgr.receive')}}</span>
                            </el-col>
                        </el-form-item>
                    </el-form>
                </template>
            </el-row>

            <!--订单信息-->
            <el-tabs v-if="openSatus">
                <el-tab-pane :label="$t('common.orderInformation')"></el-tab-pane>
            </el-tabs>
            <el-row v-if="!serviceTask">
                <!--表单筛选-->
                <el-col :span="8">
                    <el-form-item :label="$t('traceMgr.paymentConfirmNo')" label-width="31%" style="margin-bottom: 11px;margin-right: 1%">
<!--                        <base-select :options="assetCodeOptions" v-model="assetCode" @select-changed="assetCodeChanged" clearable-->
<!--                                   :placeholder="$t('common.point')" :selectedField="selectedField">-->
<!--                        </base-select>-->
                        <el-select clearable size="medium" v-model="assetCode" :placeholder="$t('common.point')" @change="assetCodeChanged">
                            <el-option
                                    v-for="item in assetCodeOptions"
                                    :key="item.assetCode"
                                    :label="item.assetCode"
                                    :value="item.assetCode">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="$t('traceMgr.supplierName')" label-width="31%" style="margin-bottom: 11px">
                        <select-supplier class="el-select" v-model="supplier" :placeholder="$t('common.point')" @selectChanged="supplierSelectChanged" :disabled="supplierDisabled"></select-supplier>
                    </el-form-item>
                </el-col>
            </el-row>

            <payment-info v-if="openSatus" :titleShow="false" :keyId="keyId" :title="$t('traceMgr.orderInfo')"></payment-info>

            <!--数据表格-->
            <el-row v-if="openSatus">
                <data-table
                        :border="true"
                        :stripe="true"
                        :columns="columns"
                        :operateBtnLayout="''"
                        :sourceData="sourceData"
                        :showSelection="true"
                        :showPage="false"
                        @selectRowChange="selectionData">

                    <!--标题 标题按钮-->
                    <template slot="headButton">
                        <el-col :span="4"><h4>{{$t('common.fileTable')}}</h4></el-col>
                        <el-col :span="20" class="textRight">
                            <btn-batch-upload class="marginRight" :btnDisplay="true" :uploadApi="batchUploadApi" @uploadSuccess="uploadSuccess"></btn-batch-upload>

                            <btn-batch-download :fileID="fileIdArr" size="small"
                                                type="primary"
                                                :downloadButtonMsg="$t('approval.batchDownload')"
                                                :classType="true"></btn-batch-download>
                        </el-col>
                    </template>

                    <!--操作-->
                    <el-table-column :label="$t('common.operate')" align="center" fixed="right" :width="180">
                        <template scope="scope">
                            <btn-upload :icon="scope.row.assetPoolMaterialGroupDetails[0].fileId !== '0' ? 'iconfont iconzhongxinshangchuan' : ''" :uploadApi="uploadApi" :classType="true" @uploadSuccess="uploadSuccess" :rowIndex="parseInt(scope.row.keyId)" :rowData="scope.row"></btn-upload>
                            <btn-download v-if="scope.row.assetPoolMaterialGroupDetails[0].fileId !== '0'" :fileID="scope.row.assetPoolMaterialGroupDetails[0].fileId"></btn-download>
                        </template>
                    </el-table-column>
                </data-table>
            </el-row>

            <!--表单-->
            <el-row v-if="openSatus" class="marginTop">
                <el-form :model="express" :rules="rules" ref="form">
                    <el-form-item :label="$t('common.courierCompany')" label-width="80px" prop="expressCompany">
                        <el-select class="form-item-class" v-model="express.expressCompany"
                                   :placeholder="$t('common.point')">
                            <el-option
                                    v-for="item in expeditedProcessOptions"
                                    :key="item.dictId"
                                    :label="item.dictName"
                                    :value="item.dictId">
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item :label="$t('common.trackingNumber')" label-width="80px" prop="expressNo">
                        <el-input v-model="express.expressNo" maxlength="20" class="form-item-class" :placeholder="$t('traceMgr.pleaseEnterPressNum')"></el-input>
                    </el-form-item>

                </el-form>
            </el-row>

          <div slot="footer" class="dialog-footer">
            <auth-button type="primary" size="medium" :label="$t('common.complete')" @click="urgentOrderList_conmit()"></auth-button>
            <el-button size="medium" @click="dialogVisible=false">{{$t('common.close')}}</el-button>
          </div>

        </dialog-edit>
        <DialogEdit
                :visible.sync="dialogConfirm"
                :title="$t('common.tip')"
                center="center"
                :width="'30%'"
                :saveLabel="$t('traceMgr.sure')"
                :closeLabel="$t('approval.cancel')"
                @onSaved="doConfirm"
                :autoSave="false" editModel="E" :form="form" :close-on-click-modal="false" class="el-dialog--center">
            <div class="text-center">{{$t('common.confirmSubmit')}}</div>
        </DialogEdit>
        <DialogEdit :autoSave="false" :autoClose="true" @close="closeKeep" @onSaved="onSavedKeep" :saveLabel="$t('traceMgr.keep')" :closeLabel="$t('traceMgr.nokeep')" editModel="E" :form="form" :visible.sync="doWhether" :title="$t('common.tip')" width="35%" :close-on-click-modal="false" class="el-dialog--center">
            <p class="text-center">{{$t('traceMgr.WhetherToKeepTheUploadedFiles')}}</p>
        </DialogEdit>
    </div>
</template>

<script>

import {
  DialogEdit,
  authButton,
  SelectSupplier,
  SelectProductName,
  dymForm,
  DataTable,
  btnBatchUpload,
  btnBatchDownload,
  btnDownload,
  btnUpload,
  validate,
  paymentInfo,
  BaseSelect
} from 'newepoch-components'
import tracemgrApi from '@/api/tracemgrApi'
import { UPLOAD_API, BATCH_UPLOAD_API } from '@/constant.js'

export default {
  name: 'sanningCopyReceivingDialog',

  props: {
    visible: {
      type: Boolean
    },
    form: {
      type: Object
    },
    serviceTask: {
      type: Boolean
    },
    pageFlag: {
      type: Boolean
    }
  },

  components: {
    UPLOAD_API,
    BATCH_UPLOAD_API,
    DialogEdit,
    SelectSupplier,
    authButton,
    SelectProductName,
    dymForm,
    DataTable,
    btnBatchUpload,
    btnBatchDownload,
    btnDownload,
    btnUpload,
    tracemgrApi,
    paymentInfo,
    BaseSelect
  },

  data () {
    return {
      supplierDisabled: false,
      uploadedFiles: [],
      nowSelectRow: [],
      selectedField: ['assetInfoId', 'assetCode'],
      supplier: '',
      assetCode: '',
      keyId: '',
      assetCodeOptions: [],
      uploadFileObj: [],
      doWhether: false,
      dialogForm: {},
      dialogApi: {},
      batchUploadApi: BATCH_UPLOAD_API,
      openSatus: false,
      uploadApi: UPLOAD_API,
      dialogConfirm: false,
      express: { expressCompany: '', expressNo: '' },
      rules: {
        expressCompany: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.courierCompanyNotEmpty,
          trigger: 'change'
        }],
        expressNo: [{
          required: true,
          message: this.$i18n.messages[this.$i18n.locale].common.courierNumberNotEmpty,
          trigger: 'blur'
        },
        { validator: validate.expressNumValidate, trigger: 'blur' }]
      },
      sourceData: [],
      tempData: [
        {
          keyId: '1',
          assetInfoId: '001',
          receiveType: 1,
          fileSource: 1
        }
      ],
      taskTypeValue: '',
      taskTypeOptions: [],
      expeditedProcessOptions: [],
      columns: [
        // 文件名称
        {
          prop: 'fileName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.fileName,
          width: '200px'
        },
        // 审核意见
        {
          prop: 'auditOpinion',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.auditOpinion,
          width: '500px'
        }],
      fileIdArr: []
    }
  },

  watch: {
    visible: {
      deep: true,
      handler: function (newVal, oldVal) {
        if (newVal) {
          this.supplierDisabled = false
          this.uploadedFiles = []
          this.sourceData = []
          this.openSatus = this.pageFlag
          this.express.expressCompany = ''
          this.express.expressNo = ''
          this.assetCode = ''
          this.supplier = ''
          if (!this.serviceTask) {
            tracemgrApi['sanningCopyReceivingDialog'].getAssetCode().then(res => {
              this.assetCodeOptions = res.data
            })
          }
          if (this.serviceTask) {
            // 工作台执行以下代码
            this.keyId = this.form.assetInfoId
            // 查询文件列表数据
            tracemgrApi['sanningCopyReceivingDialog'].getPage({ assetInfoId: this.form.assetInfoId }).then(res => {
              // this.sourceData = res.data
            })
          }
        } else {
          this.keyId = ''
        }
      }
    }
  },
  computed: {
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (val) {
        this.$emit('update:visible', val)
      }
    }
  },
  methods: {
    uploadSuccess (val) {
      if (val.fileList !== null && val.fileList !== undefined) {
        let sameName = 0
        // 如果上传的文件名称不对应弹一个提示
        let tempValue = ''
        for (let i = 0; i < val.fileList.length; i++) {
          for (let j = 0; j < this.sourceData.length; j++) {
            let tempFileName = val.fileList[i].fileName.split('.')
            // 如果名字里面有多个点
            if (tempFileName.length > 2) {
              for (let n = 0; n < tempFileName.length - 1; n++) {
                tempValue += tempFileName[n]
              }
            } else {
              tempValue = tempFileName[0]
            }
            if (tempValue === this.sourceData[j].fileName) {
              this.sourceData[j].assetPoolMaterialGroupDetails[0].fileId = val.fileList[i].keyId
              this.sourceData[j].assetPoolMaterialGroupDetails[0].productFileName = val.fileList[i].fileName
              let uploadData = { 'fileID': val.fileList[i].keyId, 'fileName': val.fileList[i].fileName, 'judgeName': tempValue }
              this.uploadedFiles.push(uploadData)
              sameName++
              break
            }
          }
        }
        if (sameName === 0) {
          this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.warningUploadA)
        } else if (sameName < val.fileList.length) {
          this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.warningUploadB)
        }
      } else {
        for (var i = 0; i < this.sourceData.length; i++) {
          if (val.rowData.keyId === this.sourceData[i].keyId) {
            this.sourceData[i].assetPoolMaterialGroupDetails[0].fileId = val.fileID
            this.sourceData[i].assetPoolMaterialGroupDetails[0].productFileName = val.fileName
            break
          }
        }
        let uploadData = { 'fileID': val.fileID, 'fileName': val.fileName, 'judgeName': val.rowData.fileName }
        this.uploadedFiles.push(uploadData)
      }
    },
    selectionData (val) {
      this.nowSelectRow = val
      this.fileIdArr = []
      for (let j = 0; j < val.length; j++) {
        this.fileIdArr.push(val[j].assetPoolMaterialGroupDetails[0].fileId)
      }
    },
    close () {
      this.dialogVisible = !this.dialogVisible
    },
    // 点击任务类型确定按钮
    taskTypeConfirm () {
      this.openSatus = true
    },
    // 当付款确认书select 如果确认保留已上传的文件时执行
    onSavedKeep () {
      // 保留已上传的文件
      this.success(this.$i18n.messages[this.$i18n.locale].traceMgr.keepedFiles)
      this.doWhether = false
    },
    // 当付款确认书select 如果确认不保留已上传的文件时执行
    closeKeep () {
      // 删除已上传的文件
      this.uploadedFiles = []
      this.success(this.$i18n.messages[this.$i18n.locale].traceMgr.deletedFiles)
      this.doWhether = false
    },
    supplierSelectChanged (val, name, row) {
      // 根据供应商查询此供应商当前未放款的订单编号
      tracemgrApi['sanningCopyReceivingDialog'].getAssetCode({ creditorId: val }).then(res => {
        this.assetCodeOptions = res.data
      })
    },
    assetCodeChanged (val) {
      if (this.uploadedFiles.length > 0) {
        // 提示是否保留已上传文件
        this.doWhether = true
      }
      // 选择付款确认书后去查询供应商
      tracemgrApi['sanningCopyReceivingDialog'].getSupplierByAssetCode({ assetCode: val }).then(res => {
        if (res.data.length > 0) {
          this.supplier = res.data[0].creditor
        }
      })
      for (let h = 0; h < this.assetCodeOptions.length; h++) {
        if (val === this.assetCodeOptions[h].assetCode) {
          // 设置订单信息的keyid
          this.keyId = this.assetCodeOptions[h].assetInfoId
        }
      }
      // 查询文件列表数据
      tracemgrApi['sanningCopyReceivingDialog'].getPage({ assetInfoId: this.keyId }).then(res => {
        this.sourceData = res.data.datas
        if (this.sourceData.length > 0) {
          if (this.uploadedFiles.length > 0) {
            for (let i = 0; i < this.uploadedFiles.length; i++) {
              for (let j = 0; j < this.sourceData.length; j++) {
                if (this.uploadedFiles[i].judgeName === this.sourceData[j].fileName) {
                  this.sourceData[j].assetPoolMaterialGroupDetails[0].fileId = this.uploadedFiles[i].fileID
                  this.sourceData[j].assetPoolMaterialGroupDetails[0].productFileName = this.uploadedFiles[i].fileName
                }
              }
            }
          }
        }
      })
      if (this.assetCode !== null && this.assetCode !== '' && this.assetCode !== undefined) {
        this.supplierDisabled = true
      }
    },
    doConfirm () {
      for (let i = 0; i < this.sourceData.length; i++) {
        let tempObj = { 'receiveId': this.sourceData[i].assetPoolMaterialGroupDetails[0].keyId,
          'assetPoolId': this.sourceData[i].assetPoolMaterialGroupDetails[0].assetPoolId,
          'assetPoolMaterialGroupId': this.sourceData[i].assetPoolMaterialGroupDetails[0].assetPoolMaterialGroupId,
          'fileCode': this.sourceData[i].assetPoolMaterialGroupDetails[0].productFileCode,
          'fileName': this.sourceData[i].assetPoolMaterialGroupDetails[0].productFileName,
          'fileId': this.sourceData[i].assetPoolMaterialGroupDetails[0].fileId,
          'expressCompany': this.express.expressCompany,
          'expressNo': this.express.expressNo,
          'receiveSource': '2',
          'receiveCopies': '1' }
        this.uploadFileObj.push(tempObj)
      }
      let tempMainObj = { 'fileSource': '1', 'receiveType': '1', 'assetInfoId': this.keyId }
      this.uploadFileObj.push(tempMainObj)
      tracemgrApi['sanningCopyReceivingDialog'].save({ batchJsonString: JSON.stringify(this.uploadFileObj) }).then(res => {
        if (res.data) {
          this.success(this.$i18n.messages[this.$i18n.locale].common.saveSuccess)
        }
        this.uploadFileObj = []
        this.dialogVisible = false
      })
      this.dialogConfirm = false
    },

    /**
       * 提交按钮
       */
    urgentOrderList_conmit () {
      this.$refs['form'].validate(result => {
        if (result) { // 验证通过，提交方法
          this.uploadFileObj = []
          this.dialogConfirm = true
        }
      })
    }
  },
  mounted () {
    // 页面初始化
    this.doWhether = false
    this.uploadFileObj = []
    // 去字典查找快递公司
    this.$store.dispatch('GetDictionary', { dictTypeCode: 'tracemgr_express_company' }).then(res => {
      this.expeditedProcessOptions = res
    })
    // 去字典查找任务类型
    this.$store.dispatch('GetDictionary', { dictTypeCode: 'tracemgr_launch_task_type' }).then(res => {
      this.taskTypeOptions = res
      this.taskTypeValue = res[0].dictName
    })
  }
}
</script>
