<template>
  <div>
    <up-down-layout :handleFlag.sync="handleFlag" :header="$t('traceMgr.uploadPerformanceDoc')"  id="uploadPerformanceFileTaskListUpDownLayout" :bottomHeight="21" ref="taskListUpDownLayout"
                    v-loading="uploadLoading" :element-loading-text="$t('traceMgr.loading')" element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, 0.7)">
      <search-form
        @clearParam="clearParam"
        @handleFilter="handleFilter"
        searchPerms="search"
        resetPerms="reset"
        :formValue.sync="queryParas"
        v-model="queryParas"
        :componentList="componentList"
        slot="query">
      </search-form>
      <template slot="table">
        <data-table :menuCode="menuId" :loadPage="loadPage" :stripe="true" :columns="columns" @selectRowChange="selectionData"
                    :api="api" :handleFlag.sync="handleFlag" :border="true" :showSelection="true" id="uploadPerformanceFile"
                    :queryParas="queryParas" :sourceData.sync="sourceData" :menuFlag="true" v-bind="elHeightObj"
                    :loadCount.sync="loadCount"  :operateBtnLayout="operateBtnLayout" :showPage="true">

          <template slot="headButton">
            <el-row>
              <el-col :span="24" class="textRight">
                <auth-button type="primary" size="medium" :label="$t('common.complete')" @click="complete()" class="iconfont icontijiao"></auth-button>
                <btn-batch-upload btnSize="medium" :btnDisplay="true" :show-file-list="true" :uploadApi="batchUploadApi" @uploadFailed="uploadFailed" @uploadSuccess="batchUploadSuccess"></btn-batch-upload>
              </el-col>
            </el-row>
          </template>
          <template slot="possibleResolutionTime" slot-scope="scope">
            <el-date-picker v-model="scope.data.row.possibleResolutionTime" type="datetime" style="width: 200px" :picker-options="expireTimeOption"></el-date-picker>
          </template>
          <el-table-column align="center" min-width="200px" :label="$t('common.operate')" fixed="right">
            <template slot-scope="scope">
              <div v-if="scope.row.getFileId === undefined || scope.row.getFileId === '0'">
                <btn-upload :classType="true" :uploadApi="uploadApi" :rowData="scope.row" @uploadSuccess="uploadSuccess" @uploadFailed="uploadFailed"></btn-upload>
              </div>
              <div v-else>
                <btn-upload :icon="'iconfont iconzhongxinshangchuan'" :fileID="scope.row.getFileId" :classType="true" :uploadApi="uploadApi" :rowData="scope.row" @uploadSuccess="uploadSuccess" @uploadFailed="uploadFailed"></btn-upload>
                <btn-download :fileID="scope.row.getFileId"></btn-download>
                <el-tooltip class="item" effect="dark" :content="$t('common.del')" placement="top">
                  <el-button @click="deleteFile(scope.row)" circle size="medium" class="iconfont iconshanchu12"></el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </data-table>
      </template>
    </up-down-layout>
  </div>
</template>
<script>
import {
  DataTable,
  btnDownload,
  btnBatchUpload,
  DialogEdit,
  btnUpload,
  SelectFlag,
  searchForm,
  upDownLayout,
  authButton,
  SelectCoreEnterprise,
  SelectPlanManager,
  SelectAreaCommissioner,
  SelectProductName,
  SelectCoreEnterpriseCascade,
  SelectSmallArea,
  SelectAllAreaCommissioner
} from 'newepoch-components'
import mixin from '@/pages/mixin'
import BasePage from '@/pages/basePage'
import tracemgrApi from '@/api/tracemgrApi'
import authcenterApi from '@/api/authcenterApi'
import componentsApi from '@/api/componentsApi'
import DatePicker from '@/components/element/DatePick.vue'
import { UPLOAD_API, BATCH_UPLOAD_API } from '@/constant.js'
import * as format from '@/filters/index'

export default {
  extends: new BasePage(),
  mixins: [mixin],
  components: {
    authButton,
    UPLOAD_API,
    BATCH_UPLOAD_API,
    BasePage,
    tracemgrApi,
    authcenterApi,
    DataTable,
    btnDownload,
    DialogEdit,
    btnUpload,
    btnBatchUpload,
    DatePicker,
    SelectFlag,
    searchForm,
    upDownLayout,
    SelectCoreEnterprise,
    SelectPlanManager,
    SelectAreaCommissioner,
    SelectProductName,
    SelectCoreEnterpriseCascade,
    format,
    SelectSmallArea,
    componentsApi,
    SelectAllAreaCommissioner
  },
  props: {
    visible: {
      type: Boolean
    },
    url: {
      type: String
    },
    needComplete: {
      type: Boolean
    },
    setLoginId: {
      type: Boolean
    }
  },
  data () {
    return {
      elOtherHeight: 150,
      tableId: 'uploadPerformanceFile',
      uploadLoading: false,
      saveLoading: false,
      uploadApi: UPLOAD_API,
      batchUploadApi: BATCH_UPLOAD_API,
      downloadId: '',
      loadPage: 'getList',
      getLoginId: false,
      handleFlag: true,
      queryParas: {
      },
      submitData: [],
      loadCount: 0,
      operateBtnLayout: '',
      sourceData: [],
      areaData: [],
      trackOrderInfoFiles: {},
      trackOrderInfoFilesFormData: [],
      selectedRows: [],
      uploadPerformanceFileList: {},
      expireTimeOption: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 8.64e7 // 禁用以前的日期，今天不禁用
          // return date.getTime() <= Date.now();    //禁用今天以及以前的日期
        }
      },
      columns: [
        // 区域
        {
          prop: 'coreAreaName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.region,
          showOverflowTooltip: true,
          width: '180px',
          spanStyle: function (row) {
            return 'color:' + row['prioritycolor']
          }
        },
        // 区域编号
        {
          prop: 'sectionNumber',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.sectionNumber,
          showOverflowTooltip: true,
          width: '180px',
          spanStyle: function (row) {
            return 'color:' + row['prioritycolor']
          }
        },
        // 项目公司名称
        {
          prop: 'nameOfProjectCompany',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.nameOfProjectCompany,
          showOverflowTooltip: true,
          width: '200px',
          spanStyle: function (row) {
            return 'color:' + row['prioritycolor']
          }
        },
        // 供应商名称
        {
          prop: 'supplierName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.supplierName,
          showOverflowTooltip: true,
          width: '200px',
          spanStyle: function (row) {
            return 'color:' + row['prioritycolor']
          }
        },
        // 付款确认书编号
        {
          prop: 'paymentConfirmationNo',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.paymentConfirmationNo,
          showOverflowTooltip: true,
          width: '250px',
          spanStyle: function (row) {
            return 'color:' + row['prioritycolor']
          }
        },
        // 应收账款金额
        {
          prop: 'amountOfReceivables',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.amountOfReceivables,
          showOverflowTooltip: true,
          width: '150px',
          format: (row) => {
            if (row.amountOfReceivables === undefined || row.amountOfReceivables === '') {
              return ''
            }
            return format.thousandFilter(row.amountOfReceivables) + '元'
          }
        },
        // 预计解决时间
        {
          prop: 'possibleResolutionTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.possibleResolutionTime,
          width: '220px',
          slot: true
        },
        // 上传时间
        {
          prop: 'uploadTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.uploadTime,
          showOverflowTooltip: true,
          width: '180px'

        },
        // 上传人
        {
          prop: 'uploadPerson',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.uploadPerson,
          showOverflowTooltip: true,
          width: '150px',
          spanStyle: function (row) {
            return 'color:' + row['prioritycolor']
          }
        },
        // 上传状态
        {
          prop: 'uploadStatus',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.uploadStatus,
          showOverflowTooltip: true,
          width: '150px',
          spanStyle: function (row) {
            return 'color:' + row['prioritycolor']
          },
          format: (row) => {
            return format.formatDict(row.uploadStatus, 'tracemgr_performance_document_status')
          }
        }
      ],
      componentList: [
        // 产品名称
        {
          value: 'productName',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.productName,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          name: 'product',
          componentName: SelectProductName,
          labelWidth: '96px'
        },
        // 核心企业
        {
          value: 'coreEnterprise',
          componentName: SelectCoreEnterprise,
          label: this.$i18n.messages[this.$i18n.locale].common.coreEnterprise,
          prop: 'coreCompanyId'
        },
        // 计划管理人
        {
          value: 'planningManagerName',
          label: this.$i18n.messages[this.$i18n.locale].common.planningManagerName,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          componentName: SelectPlanManager,
          labelWidth: '120px'
        },
        // 期数
        {
          value: 'periodsCascade',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.periodsCascade,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          componentName: 'el-input',
          type: 'number',
          labelWidth: '96px',
          maxlength: 100
        },
        // 区域
        {
          value: 'region',
          label: this.$i18n.messages[this.$i18n.locale].common.district,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          componentName: SelectSmallArea
        },
        // 区域编号
        {
          value: 'sectionNumber',
          label: this.$i18n.messages[this.$i18n.locale].common.sectionNumber,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          componentName: 'el-input',
          store: this.$store,
          labelWidth: '120px',
          maxlength: 100
        },
        // 项目公司名称
        {
          value: 'nameOfProjectCompany',
          label: this.$i18n.messages[this.$i18n.locale].common.nameOfProjectCompany,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          componentName: 'el-input',
          store: this.$store,
          labelWidth: '96px',
          maxlength: 100
        },
        // 供应商名称
        {
          value: 'supplierName',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.supplierName,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          componentName: 'el-input',
          maxlength: 100
        },
        // 付款确认书编号
        {
          value: 'paymentConfirmationNo',
          label: this.$i18n.messages[this.$i18n.locale].common.paymentConfirmationNo,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          componentName: 'el-input',
          labelWidth: '120px',
          maxlength: 100
        },
        // 上传状态
        {
          value: 'uploadStatus',
          label: this.$i18n.messages[this.$i18n.locale].common.uploadStatus,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          dictTypeCode: 'tracemgr_performance_document_status',
          componentName: 'SelectDictionary',
          labelWidth: '96px'
        },
        // 区域专员
        {
          value: 'theRegionalCommissioner',
          label: this.$i18n.messages[this.$i18n.locale].common.theRegionalCommissioner,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          componentName: SelectAllAreaCommissioner,
          multiple: true
        }
      ]
    }
  },
  created () {
    this.getLoginId = !this.getLoginId
    tracemgrApi['uploadPerformanceFileTaskDialog'].getLoginId().then(item => {
      this.queryParas.theRegionalCommissioner[1] = item.data.userId
      this.loginId = item.data.userId

      if (this.queryParas.theRegionalCommissioner[1] !== '' && this.queryParas.theRegionalCommissioner[1] !== undefined && this.queryParas.theRegionalCommissioner[1] !== null) {
        this.handleFilter()
      }
    })
  },
  computed: {
    api () {
      return tracemgrApi['uploadPerformanceFileTaskDialog']
    }
  },
  watch: {
    visible: {
      handler: function (newValue) {
        if (newValue) {
          // this.sourceData = []
          this.$nextTick(function () {
            this.handleFilter()
          })
        }
      }
    },
    sourceData: function (newValue) {
      if (newValue) {
        componentsApi.areabiz.getList().then(res => {
          if (res.data) {
            this.areaData = res.data
          }
        })
      }
    },
    getLoginId: {
      handler: function (val) {
        this.$nextTick(function () {
          // tracemgrApi['uploadPerformanceFileTaskDialog'].getLoginId().then(item => {
          //   this.queryParas.theRegionalCommissioner[1] = item.data.userId
          //   this.loginId = item.data.userId
          //
          //   if (this.queryParas.theRegionalCommissioner[1] !== '' && this.queryParas.theRegionalCommissioner[1] !== undefined && this.queryParas.theRegionalCommissioner[1] !== null) {
          //     this.handleFilter()
          //   }
          // })
          // this.timer = setInterval(() => {
          //   if (this.queryParas.theRegionalCommissioner[1] !== '' && this.queryParas.theRegionalCommissioner[1] !== undefined && this.queryParas.theRegionalCommissioner[1] !== null) {
          //     this.handleFilter()
          //     clearInterval(this.timer)
          //   }
          // }, 200)
        })
      }
    }
  },
  methods: {
    clearParam () {
      this.queryParas = {
        theRegionalCommissioner: [this.loginId],
        pageIndex: 1,
        pageSize: 10
      }
    },
    initLayout: function () {
      this.initStyle()
    },
    closeDialog () {
      this.dialogVisible = false
    },
    handleFilter: function () {
      this.loadCount = this.loadCount + 1
    },
    uploadSuccess (returnData, rowData) {
      let $this = this
      $this.trackOrderInfoFiles.fileName = returnData.fileName
      $this.trackOrderInfoFiles.fileType = 1
      $this.trackOrderInfoFiles.fileId = returnData.fileID
      $this.trackOrderInfoFiles.feedbackContent = ''
      $this.trackOrderInfoFiles.fileSource = 3
      $this.trackOrderInfoFilesFormData.push($this.trackOrderInfoFiles)

      let data = {}
      if (rowData.uploadPerformanceFileDTOList.length > 0) {
        for (let i = 0; i < rowData.uploadPerformanceFileDTOList.length; i++) {
          if (rowData.uploadPerformanceFileDTOList[i].fileSource === 3) {
            data['keyId'] = rowData.uploadPerformanceFileDTOList[i].keyId
            data['type'] = 'update'
            break
          } else if (i === rowData.uploadPerformanceFileDTOList.length - 1) {
            data['type'] = 'save'
          }
        }
      } else {
        data['type'] = 'save'
      }
      data['fileName'] = returnData.fileName
      data['fileId'] = returnData.fileID
      data['assetCode'] = rowData.paymentConfirmationNo
      data['assetInfoId'] = rowData.assetInfoId
      data['instanceId'] = rowData.instanceId
      data['trackOrderInfoFiles'] = JSON.stringify($this.trackOrderInfoFilesFormData)
      data['projectId'] = rowData.projectId

      this.uploadLoading = true
      tracemgrApi['uploadPerformanceFileTaskDialog'].upload(data).then(res => {
        if (res.data) {
          this.uploadLoading = false
          this.success(this.$i18n.messages[this.$i18n.locale].traceMgr.file + returnData.fileName + this.$i18n.messages[this.$i18n.locale].common.uploadSuccess)
          rowData.fileId = returnData.fileID
          rowData.fileName = returnData.fileName
          rowData.getFileId = returnData.fileID
          $this.trackOrderInfoFilesFormData = []
          this.handleFilter()
        } else {
          this.uploadLoading = false
          this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.fileEorro)
        }
      }).catch(res => {
        $this.uploadLoading = false
      })
    },
    batchUploadSuccess (returnData) {
      let $this = this
      let data = {}
      data['fileType'] = 1
      data['feedbackContent'] = ''
      data['fileSource'] = 3
      data['fileList'] = JSON.stringify(returnData.fileList)

      this.uploadLoading = true
      tracemgrApi['uploadPerformanceFileTaskDialog'].batchUpload(data).then(res => {
        if (res.data.trueOrFalse) {
          // this.uploadLoading.close()
          this.uploadLoading = false
          if (res.data.faileFileName.length > 0) {
            this.success(this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage1 + returnData.fileName + this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage2 + res.data.successNum + this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage4 + res.data.faileFileName + this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage5)
          } else {
            this.success(this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage1 + returnData.fileName + this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage2 + res.data.successNum + this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage3)
          }
          this.handleFilter()
        } else {
          // this.uploadLoading = false
          this.uploadLoading = false
          if (res.data.faileFileName.length > 0) {
            this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage1 + returnData.fileName + this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage6 + res.data.successNum + this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage4 + res.data.faileFileName + this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage5)
          } else {
            this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage1 + returnData.fileName + this.$i18n.messages[this.$i18n.locale].traceMgr.uploadMessage7)
          }
        }
      }).catch(res => {
        $this.uploadLoading = false
      })
    },
    uploadFailed: function (a, b, c) {
      this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.fileEorro)
    },
    selectionData (value) {
      this.selectedRows = value
    },
    complete () {
      // 验证提交数据
      let selectedRows = this.selectedRows
      let today = new Date()
      if (selectedRows.length > 0) {
        for (let i = 0; i < selectedRows.length; i++) {
          if (selectedRows[i].getFileId === null || selectedRows[i].getFileId === undefined) {
            // 预计解决时间(空值)
            if (selectedRows[i].possibleResolutionTime === null || selectedRows[i].possibleResolutionTime === undefined) {
              this.$message({
                message: this.$i18n.messages[this.$i18n.locale].traceMgr.submitMessage1 + selectedRows[i].paymentConfirmationNo + this.$i18n.messages[this.$i18n.locale].traceMgr.submitMessage2,
                type: 'error'
              })
              return
            } else if (selectedRows[i].possibleResolutionTime < today) {
              // 预计解决时间(不有小余当前日期)
              this.$message({
                message: this.$i18n.messages[this.$i18n.locale].traceMgr.submitMessage1 + selectedRows[i].paymentConfirmationNo + this.$i18n.messages[this.$i18n.locale].traceMgr.submitMessage3,
                type: 'error'
              })
              return
            }
          }
          this.trackOrderInfoFiles.fileName = selectedRows[i].fileName
          this.trackOrderInfoFiles.fileType = '1'
          this.trackOrderInfoFiles.fileId = selectedRows[i].fileId
          this.trackOrderInfoFiles.feedbackContent = ''
          this.trackOrderInfoFiles.fileSource = 3
          this.trackOrderInfoFilesFormData.push(this.trackOrderInfoFiles)

          let data = {}
          let $this = this
          data['projectId'] = selectedRows[i].projectId
          data['estimatedFinishTime'] = selectedRows[i].possibleResolutionTime
          data['instanceId'] = selectedRows[i].instanceId
          data['assetCode'] = selectedRows[i].paymentConfirmationNo
          data['trackOrderInfoFiles'] = JSON.stringify($this.trackOrderInfoFilesFormData)
          data['fileId'] = selectedRows[i].getFileId
          this.submitData.push(data)
        }
        if (this.submitData.length > 0) {
          this.saveLoading = this.$loading({
            lock: true,
            text: this.$i18n.messages[this.$i18n.locale].traceMgr.loading,
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          tracemgrApi['uploadPerformanceFileTaskDialog'].submit(this.submitData).then(res => {
            if (res.data) {
              this.saveLoading.close()
              this.success(this.$i18n.messages[this.$i18n.locale].common.submittedSuccessfully)
              this.submitData = []
              this.trackOrderInfoFilesFormData = []
              this.handleFilter()
            } else {
              this.saveLoading.close()
              this.error(this.$i18n.messages[this.$i18n.locale].common.submitFail)
            }
          })
        }
      } else {
        this.$message({
          message: this.$i18n.messages[this.$i18n.locale].traceMgr.selectMessage,
          type: 'error'
        })
      }
    },
    fileIdCheck (row) {
      for (let i = 0; i < row.uploadPerformanceFileDTOList.length; i++) {
        if (row.uploadPerformanceFileDTOList[i].fileId !== null && row.uploadPerformanceFileDTOList[i].fileId !== '' && row.uploadPerformanceFileDTOList[i].fileId !== undefined) {
          this.uploadPerformanceFileList = row.uploadPerformanceFileDTOList[i]
          return true
        } else {
          return false
        }
      }
    },
    formatArea (value) {
      for (let i = 0; i < this.areaData.length; i++) {
        if (value === this.areaData[i].keyId) {
          return this.areaData[i].areaName
        } else {
          if (i === this.areaData.length - 1) {
            return value
          }
        }
      }
    },
    deleteFile: function (row) {
      let $this = this
      $this.trackOrderInfoFilesFormData = []
      // $this.trackOrderInfoFiles.fileName = returnData.fileName
      $this.trackOrderInfoFiles.fileType = 1
      // $this.trackOrderInfoFiles.fileId = returnData.fileID
      $this.trackOrderInfoFiles.feedbackContent = ''
      $this.trackOrderInfoFiles.fileSource = 3
      $this.trackOrderInfoFilesFormData.push($this.trackOrderInfoFiles)

      let data = {}
      // data['fileName'] = returnData.fileName
      data['fileId'] = '0'
      data['assetCode'] = row.paymentConfirmationNo
      data['assetInfoId'] = row.assetInfoId
      data['instanceId'] = row.instanceId
      data['trackOrderInfoFiles'] = JSON.stringify($this.trackOrderInfoFilesFormData)
      data['projectId'] = row.projectId

      this.uploadLoading = true
      tracemgrApi['uploadPerformanceFileTaskDialog'].deleteFile(data).then(res => {
        if (res.data) {
          this.success(this.$i18n.messages[this.$i18n.locale].common.delSuccess)
          row.fileId = '0'
          row.fileName = ''
          row.getFileId = '0'
          $this.trackOrderInfoFilesFormData = []
          this.uploadLoading = false
        } else {
          this.error(this.$i18n.messages[this.$i18n.locale].common.delFailure)
          this.uploadLoading = false
        }
      }).catch(res => {
        this.error(this.$i18n.messages[this.$i18n.locale].common.delFailure)
        $this.uploadLoading = false
      })
    }
  }
}
</script>

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