<template>
    <div element-loading-spinner="el-icon-loading">
        <up-down-layout :handleFlag.sync="handleFlag"  id="originalSupplementaryMailTaskListUpDownLayout" :bottomHeight="21" ref="taskListUpDownLayout">
        <!--原件补寄页面-->
        <search-form :componentList="searchList" :formValue.sync="queryParas" v-model="queryParas" searchPerms="search" resetPerms="reset"
                     @handleFilter="handleFilter" @clearParam="clearParam" slot="query">
        </search-form>
            <template slot="table">
                <el-form :model="formTableData" ref="formTableData" :show-message="false">
                    <data-table :sourceData.sync="formTableData.sourceData" id="OriginalPost"
                                :api="api" v-bind="elHeightObj"
                                :columns="columns"
                                :loadCount.sync="loadCount"
                                :border="true"
                                :stripe="true"
                                :showSelection="true"
                                @selection-change="changeFun"
                                operateBtnLayout=""
                                :loadPage="loadPage"
                                :queryParas="queryParas" :menuFlag="true">
                        <template slot="Remarks">
                            <el-row>
                                <el-input type="textarea" v-model="opinion" :autosize="autosize"></el-input>
                            </el-row>
                        </template>
                        <!--表右上方按钮-->
                        <template slot="headButton">
                          <el-row>
                            <el-col :span="24" class="btn-right">
                              <auth-button type="primary" :loading="loading" size="medium" @click="complete" :label="$t('common.complete')" class="iconfont icontijiao"></auth-button>
                              <auth-button type="primary" :loading="exportLoading"  size="medium" @click="exportFile" :label="$t('common.export')" class="iconfont icondaochu"></auth-button>
                            </el-col>
                          </el-row>
                        </template>
                        <template slot="estimatedFinishTime" slot-scope="scope">
                            <el-row>
                                <el-date-picker :picker-options="expireTimeOption" v-model="scope.data.row.estimatedFinishTime"></el-date-picker>
                            </el-row>
                        </template>
                        <template slot="memo" slot-scope="scope">
                            <el-row>
                                <el-input type="textarea" autosize v-model="scope.data.row.memo"></el-input>
                            </el-row>
                        </template>
                        <el-table-column align="center"
                                         min-width="80px"
                                         :label="$t('common.operate')"
                                         fixed="right">
                            <template slot-scope="scope">
                              <el-tooltip class="item" effect="dark" :content="$t('common.download')" placement="top">
                                <el-button @click="downloadSuccess(scope.row)" circle size="mini" class="iconfont iconxiazai"></el-button>
                              </el-tooltip>
                            </template>
                        </el-table-column>
                    </data-table>
                </el-form>
            </template>
        </up-down-layout>
        <file-download-dialog :editModel="'V'" :form="form"  :visible.sync="viewFileDown" :closeDownBatch="downloadSuccess"></file-download-dialog>
    </div>
</template>
<script>
import {
  DialogEdit,
  searchForm,
  speechCraftInput,
  btnBatchDownload,
  DataTable,
  SelectCoreEnterprise,
  SelectAreaCommissioner,
  btnDownload,
  SelectDictionary,
  upDownLayout,
  SelectSmallArea,
  SelectFinancialInstitutionsCascade,
  authButton } from 'newepoch-components'
import FileDownloadDialog from '@/components/tracemgr/common/businessFileDownloadDialog.vue'
import tracemgrApi from '@/api/tracemgrApi'
import SelectKernelEnterprise from '@/components/element/SelectKernelEnterprise'
import BasePage from '@/pages/basePage'
import * as format from '@/filters/index'
import mixin from '@/pages/mixin'
import fileApi from '@/api/fileApi'
import { downFile } from '@/utils/devUtils'
export default {
  extends: new BasePage(),
  name: 'taskDialog',
  mixins: [mixin],
  components: {
    DialogEdit,
    tracemgrApi,
    SelectDictionary,
    SelectKernelEnterprise,
    authButton,
    searchForm,
    SelectCoreEnterprise,
    FileDownloadDialog,
    btnDownload,
    upDownLayout,
    format,
    SelectSmallArea,
    btnBatchDownload,
    speechCraftInput,
    SelectFinancialInstitutionsCascade,
    fileApi,
    DataTable
  },
  mounted () {
    this.handleFilter()
  },
  data () {
    return {
      elOtherHeight: 150,
      tableId: 'OriginalPost',
      loading: false,
      exportLoading: false,
      handleFlag: true,
      viewFileDown: false,
      expireTimeOption: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7 // 禁用以前的日期，今天不禁用
          // return date.getTime() <= Date.now();    //禁用今天以及以前的日期
        }
      },
      // 多选行
      checkBoxData: [],
      loadPage: 'getList',
      loadCount: 0,
      formTableData: {
        sourceData: [
        ]
      },
      queryParas: {
        pageIndex: 1,
        pageSize: 10,
        coreEnterprise: '',
        district: [],
        nameOfCompany: '',
        supplierName: '',
        nameOfTheContract: '',
        paymentConfirmationNo: '',
        sectionNumber: '',
        fileType: '',
        fileName: '',
        theRegionalCommissioner: [this.$store.getters.userId]
      },
      form: {},
      searchList: [
        // 核心企业（下拉）
        {
          label: this.$i18n.messages[this.$i18n.locale].common.coreEnterprise,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          value: 'coreEnterprise',
          componentName: SelectKernelEnterprise,
          store: this.$store,
          labelWidth: '82px'
        },
        //   区域（下拉）
        {
          value: 'district',
          disabled: false,
          componentName: SelectSmallArea,
          name: 'productType',
          label: this.$i18n.messages[this.$i18n.locale].common.district,
          cols: [24, 24, 24, 24],
          prop: 'district',
          multiple: true,
          labelWidth: '110px'
        },
        //   项目公司名称（输入）
        {
          value: 'nameOfCompany',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          disabled: false,
          componentName: 'el-input',
          name: 'NameOfProjectCompany',
          label: this.$i18n.messages[this.$i18n.locale].common.nameOfProjectCompany,
          cols: [24, 24, 24, 24],
          prop: 'nameOfProjectCompany',
          labelWidth: '120px'
        },
        //   供应商名称（输入）
        {
          value: 'supplierName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          disabled: false,
          componentName: 'el-input',
          name: 'supplierName',
          label: this.$i18n.messages[this.$i18n.locale].common.supplierName,
          cols: [24, 24, 24, 24],
          prop: 'supplierName',
          labelWidth: '82px'
        },
        //   合同名称（输入）
        {
          value: 'nameOfTheContract',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          disabled: false,
          componentName: 'el-input',
          name: 'nameOfTheContract',
          label: this.$i18n.messages[this.$i18n.locale].common.nameOfTheContract,
          cols: [24, 24, 24, 24],
          prop: 'nameOfTheContract',
          labelWidth: '110px'
        },
        //   付款确认书编号（输入）
        {
          value: 'paymentConfirmationNo',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          disabled: false,
          componentName: 'el-input',
          name: 'paymentConfirmationNo',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.paymentConfirmationNo,
          cols: [24, 24, 24, 24],
          prop: 'paymentConfirmationNo',
          labelWidth: '120px'
        },
        //   区域编号（输入）
        {
          value: 'sectionNumber',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          disabled: false,
          componentName: 'el-input',
          name: 'SectionNumber',
          label: this.$i18n.messages[this.$i18n.locale].common.sectionNumber,
          cols: [24, 24, 24, 24],
          prop: 'sectionNumber',
          labelWidth: '82px'
        },
        //   文件类型（下拉）
        {
          value: 'fileType',
          disabled: false,
          componentName: SelectDictionary,
          dictTypeCode: 'tracemgr_original_file_type',
          name: 'fileType',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.fileType,
          cols: [24, 24, 24, 24],
          prop: 'fileType',
          labelWidth: '110px'
        },
        //   文件名称（输入）
        {
          value: 'fileName',
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          disabled: false,
          componentName: 'el-input',
          name: 'fileName',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.fileName,
          cols: [24, 24, 24, 24],
          prop: 'fileName',
          labelWidth: '120px'
        },
        //   区域专员（下拉）
        {
          value: 'theRegionalCommissioner',
          disabled: false,
          componentName: SelectAreaCommissioner,
          name: 'TheRegionalCommissioner',
          label: this.$i18n.messages[this.$i18n.locale].common.theRegionalCommissioner,
          cols: [24, 24, 24, 24],
          prop: 'theRegionalCommissioner',
          multiple: true,
          labelWidth: '82px'
        }
      ],
      columns: [
        {
          prop: 'coreEnterpriseName',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].common.coreEnterprise,
          align: 'left',
          width: 100
        },
        {
          prop: 'coreAreaName',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].common.district,
          align: 'left',
          width: 100
        },
        {
          prop: 'debtor',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].common.nameOfProjectCompany,
          align: 'left',
          width: 100
        },
        {
          prop: 'creditor',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].common.supplierName,
          align: 'left',
          width: 100
        },
        {
          prop: 'basicContractName',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].common.nameOfTheContract,
          align: 'left',
          width: 100
        },
        {
          prop: 'assetCode',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.paymentConfirmationNo,
          align: 'left',
          width: 140
        },
        {
          prop: 'regionCode',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].common.sectionNumber,
          align: 'left',
          width: 100
        },
        {
          prop: 'fileType',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.fileType,
          align: 'left',
          width: 100,
          format: function (row) {
            return format.formatDict(row.fileType + '', 'tracemgr_original_file_type')
          }
        },
        {
          prop: 'fileName',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.fileName,
          align: 'left',
          width: 100
        },
        {
          prop: 'auditMemo',
          showOverflowTooltip: true,
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.documentReviewOpinion,
          align: 'left',
          width: 100
        },
        {
          prop: 'estimatedFinishTime',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.estimatedRecoveryTime,
          align: 'left',
          width: 180,
          slot: true
        },
        {
          prop: 'memo',
          label: this.$i18n.messages[this.$i18n.locale].common.remarks,
          align: 'left',
          width: 140,
          slot: true
        }
      ]
    }
  },
  computed: {
    api () {
      return tracemgrApi['ementaryMailTaskDialogs']
    }
  },
  methods: {
    exportFile () {
      let $this = this
      $this.exportLoading = true
      tracemgrApi['ementaryMailTaskDialogs'].download(this.queryParas).then(res => {
        if (res.success) {
          fileApi.file.download({ keyId: res.data }).then(res => {
            downFile(res)
            $this.exportLoading = false
          }).catch(() => {
            $this.exportLoading = false
          })
        } else {
          $this.exportLoading = false
          $this.error(this.$i18n.messages[this.$i18n.locale].ladingManageList.exportFaile)
        }
      }, res => {
        this.$message({
          message: this.$i18n.messages[this.$i18n.locale].traceMgr.loadFileEorreMessage,
          type: 'warring'
        })
        $this.exportLoading = false
      })
      //   downFile(res)
    },
    clearParam () {
      this.queryParas = {
        pageIndex: 1,
        pageSize: 10,
        theRegionalCommissioner: [this.$store.getters.userId]
      }
    },
    initLayout: function () {
      this.initStyle()
    },
    complete () {
      if (this.checkBoxData.length < 1) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.messageWorning)
        return false
      }
      this.loading = true
      let $this = this
      // 提交
      this.loading = true
      let message = this.formTableData.sourceData
      let submitInfo = []
      let sum = 0
      message.forEach(item => {
        // 判断所有行数据，是否上传文件，如果没有上传文件单单是修改备注信息也不会影响保存
        if (item.memo === '') {
          item.memo = undefined
        }
        if (item.memoCopy === '') {
          item.memoCopy = undefined
        }
        if (item.estimatedFinishTime === '') {
          item.estimatedFinishTime = undefined
        }
        if (item.estimatedFinishTimeCopy === '') {
          item.estimatedFinishTimeCopy = undefined
        }
        if (item.memo !== item.memoCopy || item.estimatedFinishTime !== item.estimatedFinishTimeCopy) {
          sum = sum + 1
          submitInfo.push(item)
        }
        // 这里为了防止 不刷新页面 重复提交，修改行数据中的saveMessage标记为true 表示已经保存过了
        if (!item.saveMessage) {
          item.saveMessage = true
        }
      })
      if (sum === 0) {
        this.formTableData.sourceData.forEach(item => {
          item.saveMessage = false
        })
        this.warning(this.$i18n.messages[this.$i18n.locale].traceMgr.PleaseEditTimeClickSaveButton)
        this.loading = false
        return
      }
      if (submitInfo.length === 0) {
        this.formTableData.sourceData.forEach(item => {
          item.saveMessage = false
        })
        this.warning(this.$i18n.messages[this.$i18n.locale].traceMgr.UKSubmitInfoOrSaveSUCed)
        this.loading = false
        return
      }

      tracemgrApi['ementaryMailTaskDialogs'].save(submitInfo).then(res => {
        if (res.success) {
          this.formTableData.sourceData.forEach(item => {
            item.saveMessage = false
          })
          this.success(this.$i18n.messages[this.$i18n.locale].common.submittedSuccessfully)
          this.handleFilter()
          $this.loading = false
        } else {
          this.error(this.$i18n.messages[this.$i18n.locale].common.submitFail)
          $this.loading = false
        }
      }, res => {
        this.sourceData.forEach(item => {
          item.saveMessage = false
        })
        this.error(this.$i18n.messages[this.$i18n.locale].common.submitFail)
        $this.loading = false
      })
    },
    handleExport: function () {
      let $this = this
      tracemgrApi['ementaryMailTaskDialogs'].getList($this.queryParas)
    },
    downloadSuccess (row) {
      this.form = Object.assign({}, row)
      this.viewFileDown = !this.viewFileDown
    },
    changeFun (val) {
      this.checkBoxData = val
    }
  }
}
</script>

<style lang="scss" scoped>
  @import './src/styles/tracemgr/regionalCommissioner/taskTable/originalPost.scss';
</style>
