<template>
  <div>
    <up-down-layout :handleFlag.sync="handleFlag" :headr="$t('crm.basicInfoManage')">
      <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">
        <el-form :model="formTableData" ref="formTableData" :show-message="false">
          <data-table :api="api" :menuFlag="true"  :handleFlag.sync="handleFlag" :loadPage="loadPage"
                      v-bind="elHeightObj"
                      :queryParas="queryParas" :sourceData.sync="sourceData" :border="true" :stripe="true"
                      :loadCount.sync="loadCount" :columns="columns" :operateBtnLayout="operateBtnLayout"
                      >
            <template slot="applyReallocationFlag" slot-scope="{data}">
              <span v-if="!data.row.self">{{data.row.applyReallocationFlag===0?'否':'是'}}</span>
              <el-select v-if="data.row.self" :value="data.row.applyReallocationFlag" @change="change($event,data.row)">
                <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
              </el-select>
            </template>

            <template slot="reallocationReason" slot-scope="{data}">
              <!--<el-button v-if="data.row.reallocationReason && data.row.self"-->
                         <!--@click="inputAgainAllocationReason(data.row)" style="border: 0px; color: #1E90E9" size="mini" class="iconfont iconbianji"></el-button>-->
              <!--<i class="el-icon-edit"  v-if="data.row.reallocationReason && data.row.self" @click="inputAgainAllocationReason(data.row)" style="color: #0F78EE; font-size: 18px"></i>-->
              <i  class="iconfont iconbianji" v-if="data.row.reallocationReason && data.row.self" @click="inputAgainAllocationReason(data.row)"
                  style="color: #0F78EE; font-size: 18px; cursor: pointer"></i>
              <span>{{data.row.reallocationReason}}</span>
            </template>

            <template slot="headButton">
              <el-row>
                <el-col :span="24" class="textRight">
                  <auth-button v-if="isManage" size="medium" type="primary" :loading="isLoading" @click="handleExport" :label="$t('common.export')" class="iconfont icondaochu"></auth-button>
                  <auth-button v-if="isManage" size="medium" type="primary" :loading="isLoading2" @click="onPickFile" :label="$t('common.import')" class="iconfont icondaoru"></auth-button>
                  <auth-button v-if="needSave" size="medium" type="primary" :loading="isLoading3" @click="save" :label="$t('common.save')" class="iconfont iconbaocun11"></auth-button>
                  <input type="file" ref="fileInput" accept="*/*" @change="fileUpload" style="display: none" >
                </el-col>
              </el-row>
              <el-row>
                <!--错误消息-->
                <el-col v-if="faileFileId!==''">
                  <div class="margin-left24" v-if="faileFileId!==''">
                    <span>{{$t('common.uploadFileErrorMsg')}}
                      <a :title="$t('traceMgr.errorFile')" class="errorFile" :loading="showLoading"
                      @click="downLoadErrorFile()">{{faileFileId}}({{$t('traceMgr.clickLook')}})</a>
                    </span>
                  </div>
                </el-col>
              </el-row>
            </template>
            <el-table-column :label="$t('common.operate')" align="center" fixed="right" :width="200">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="$t('common.details')" placement="top">
                  <el-button @click="allocationDetails(scope.row)" circle size="mini" class="iconfont iconmore">
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </data-table>
        </el-form>
      </template>
    </up-down-layout>
    <supplier-distribution-history-dialog ref="historyDialog" :creditorId="this.creditorId" :visible.sync="isShowAllocationDetails" :editModel="editModel" :form="item"></supplier-distribution-history-dialog>
    <input-re-distribution-resion-dialog ref="resionDialog" :visible.sync="isShowInputAgainAllocationReason" :editModel="editModel" :form="item" @transfer="setReason"></input-re-distribution-resion-dialog>
  </div>
</template>
<script>
import BasePage from '@/pages/basePage'
import * as format from '@/filters/index'
import mixin from '@/pages/mixin'
import { DataTable, authButton, searchForm, upDownLayout, SelectAddress, SelectCoreEnterprise, SelectCoreEnterpriseCascade, SelectFactoringCommissioner, btnImport } from 'newepoch-components'
import DatePicker from '@/components/element/DatePick.vue'
import supplierDistributionHistoryDialog from '@/components/tracemgr/supplierDistribution/supplierDistributionHistoryDialog'
import inputReDistributionResionDialog from '@/components/tracemgr/supplierDistribution/inputReDistributionResionDialog'
import SelectFlag from '@/components/tracemgr/common/SelectFlag'
import tracemgrApi from '@/api/tracemgrApi'
import fileApi from '@/api/fileApi.js'
import { downFile } from '@/utils/devUtils'
// import { getUserInfo } from '../../../api/tracemgr/supplierDistribution/supplierDistributionApiList'
export default {
  extends: new BasePage(),
  name: 'supplierDistributionList',
  mixins: [mixin],
  components: {
    authButton,
    searchForm,
    upDownLayout,
    SelectAddress,
    format,
    SelectFlag,
    DataTable,
    SelectCoreEnterprise,
    SelectCoreEnterpriseCascade,
    SelectFactoringCommissioner,
    supplierDistributionHistoryDialog,
    inputReDistributionResionDialog,
    DatePicker,
    btnImport
  },
  mounted () {
    this.handleFilter()
  },
  data: function () {
    return {
      showLoading: false,
      faileFileId: '',
      editModel: '',
      // 供应商分配详情弹框是否展示
      isShowAllocationDetails: false,
      // 录入重新分配的原因弹框是否展示
      isShowInputAgainAllocationReason: false,
      styles: '',
      buttonDisable: false,
      needComplete: true,
      currentTotal: 0,
      loadPage: 'getPage',
      loadCount: 0,
      operateBtnLayout: '',
      employeeNum: '10',
      creditorId: '',
      sourceData: [],
      formTableData: {
        sourceData: []
      },
      queryParas: {
        pageIndex: 1,
        pageSize: 10,
        supplierName: '',
        factoringCommissioner: '',
        coreEnterprise: '',
        onJobStatus: '',
        group: '',
        isAgainAllocation: ''
      },
      item: {},
      showOperation: true,
      handleFlag: true,
      options: [{
        value: 0,
        label: '否'
      }, {
        value: 1,
        label: '是'
      }],
      inputModel: {},
      needSave: false,
      needExport: false,
      isManage: false, // 是否是经理角色
      isLoading: false,
      isLoading2: false,
      isLoading3: false,
      opendcreditorAllocationId: '',
      componentList: [
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.supplierName,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input + this.$i18n.messages[this.$i18n.locale].traceMgr.formerName,
          value: 'supplierName',
          labelWidth: '83px',
          componentName: 'el-input'
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.factoringCommissioner,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          value: 'factoringCommissioner',
          componentName: SelectFactoringCommissioner,
          store: this.$store
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.coreEnterprise,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          value: 'coreEnterprise',
          componentName: SelectCoreEnterprise,
          store: this.$store
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.onJobStatus,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          value: 'onJobStatus',
          dictTypeCode: 'tracemgr_employee_job_status',
          componentName: 'SelectDictionary',
          filterable: true,
          labelWidth: '83px',
          store: this.$store
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.group,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          value: 'group',
          componentName: 'el-input'
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.isAgainAllocation,
          value: 'isAgainAllocation',
          options: [{ label: '否', value: 0 }, { label: '是', value: 1 }],
          componentName: SelectFlag
        }
      ],
      columns: [
        {
          prop: 'supplierName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.supplierName,
          showOverflowTooltip: true,
          width: '200px'
        },
        {
          prop: 'historyName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.historyName,
          showOverflowTooltip: true,
          width: '200px'
        },
        {
          prop: 'natureOfEnterprise',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.natureOfEnterprise,
          showOverflowTooltip: true,
          width: '200px',
          format: function (row) {
            return format.formatDict(row.natureOfEnterprise, 'enterprise_nature')
          }
        },
        {
          prop: 'businessBeginTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.businessBeginTime,
          showOverflowTooltip: true,
          width: '200px'
        },
        {
          prop: 'businessStatus',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.businessStatus,
          showOverflowTooltip: true,
          width: '200px',
          format: function (row) {
            if (row.businessStatus === '-1') {
              return ''
            } else {
              return format.formatDict(row.businessStatus, 'biz_status')
            }
          }
        },
        {
          prop: 'orderFrequency',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.orderFrequency,
          showOverflowTooltip: true,
          width: '200px'
        },
        {
          prop: 'sealWay',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.sealWay,
          showOverflowTooltip: true,
          width: '200px',
          format: (row) => {
            let val = format.formatDict(row.sealWay, 'tracemgr_seal_type')
            if (row.sealWay === undefined || val === row.sealWay) {
              val = ''
            }
            return val
          }
        },
        {
          prop: 'numberOfCounterpart',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.numberOfCounterpart,
          showOverflowTooltip: true,
          width: '200px'
        },
        {
          prop: 'operatingDifficultyLevel',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.operatingDifficultyLevel,
          showOverflowTooltip: true,
          width: '200px',
          format: function (row) {
            if (row.operatingDifficultyLevel === '-1') {
              return ''
            } else {
              return format.formatDict(row.operatingDifficultyLevel, 'opt_difficulty_level')
            }
          }
        },
        {
          prop: 'coreEnterprise',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].common.coreEnterprise,
          showOverflowTooltip: true,
          width: '200px'
        },
        {
          prop: 'formerFactoringCommissioner',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.formerFactoringCommissioner,
          showOverflowTooltip: true,
          width: '200px'
        },
        {
          prop: 'factoringUserName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.factoringCommissioner,
          showOverflowTooltip: true,
          width: '200px'
        },
        {
          prop: 'onJobStatus',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.onJobStatus,
          showOverflowTooltip: true,
          width: '200px',
          format: function (row) {
            return format.formatDict(row.jobStatus, 'tracemgr_employee_job_status')
          }
        },
        {
          prop: 'groupName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.group,
          showOverflowTooltip: true,
          width: '200px'
        },
        {
          prop: 'maintenanceTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.maintenanceTime,
          showOverflowTooltip: true,
          width: '200px',
          format: function (row) {
            let start = ''
            let date = new Date(row.maintenanceTime)
            let y = date.getFullYear()
            let MM = date.getMonth() + 1
            MM = MM < 10 ? ('0' + MM) : MM
            let d = date.getDate()
            d = d < 10 ? ('0' + d) : d
            let h = date.getHours()
            h = h < 10 ? ('0' + h) : h
            let m = date.getMinutes()
            m = m < 10 ? ('0' + m) : m
            let s = date.getSeconds()
            s = s < 10 ? ('0' + s) : s
            start = y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
            return start
          }
        },
        {
          prop: 'applyReallocationFlag',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.isAgainAllocation,
          showOverflowTooltip: true,
          width: '200px',
          slot: true
        },
        {
          prop: 'reallocationReason',
          align: 'left',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.againAllocationReason,
          showOverflowTooltip: true,
          width: '200px',
          slot: true
        }
      ]
    }
  },
  computed: {
    api () {
      // return ''
      return tracemgrApi['supplierDistributionApiList']
    }
  },
  created: function () {
    tracemgrApi['supplierDistributionApiList'].getUserInfo('').then(res => {
      this.isManage = res.data.role === '4'
      this.isLoading = false
    }, res => {
      this.isLoading = false
    })
  },
  watch: {
    sourceData () {
      let num = 0
      let num2 = 0
      this.sourceData.forEach(item => {
        if (item.self) {
          num++
        }
        if (item.applyReallocationFlag === 1) {
          num2++
        }
      })
      if (num > 0) {
        this.needSave = true
      } else {
        this.needSave = false
      }
      if (num2 > 0) {
        this.needExport = true
      } else {
        this.needExport = false
      }
    }
  },
  methods: {
    allocationDetails: function (row) {
      let $this = this
      // $this.item = Object.assign({}, row)
      this.creditorId = row.creditorAllocationId + ''
      console.log(this.addTime)
      this.$refs.historyDialog.setData(row.creditorAllocationId + '', row.supplierName, row.addTime)
      $this.isShowAllocationDetails = true
    },
    change: function (data, el) {
      if (el.applyReallocationFlag !== data) {
        el.applyReallocationFlag = data
        this.inputModel[el.creditorAllocationId] = el
        if (data === 1) {
          let $this = this
          $this.opendcreditorAllocationId = el.creditorAllocationId
          $this.item = Object.assign({}, el)
          $this.$refs.resionDialog.setTextarea(el.reallocationReason)
          $this.isShowInputAgainAllocationReason = true
        }
      }
    },
    setReason: function (val) {
      this.inputModel[this.opendcreditorAllocationId].reallocationReason = val
    },
    inputAgainAllocationReason: function (row) {
      this.inputModel[row.creditorAllocationId] = row
      let $this = this
      $this.item = Object.assign({}, row)
      $this.$refs.resionDialog.setTextarea($this.item.reallocationReason)
      $this.isShowInputAgainAllocationReason = true
      $this.opendcreditorAllocationId = row.creditorAllocationId
    },
    handleExport: function () {
      if (!this.needExport) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.message3)
        return
      }
      let $this = this
      this.isLoading = true
      tracemgrApi['supplierDistributionApiList'].exportExcel($this.queryParas).then(res => {
        if (res.success) {
          fileApi.file.download({ keyId: res.data }).then(res => {
            downFile(res)
            $this.isLoading = false
          }).catch(() => {
            $this.isLoading = false
          })
        } else {
          $this.isLoading = false
          $this.error(this.$i18n.messages[this.$i18n.locale].ladingManageList.exportFaile)
        }
      }).catch(() => {
        $this.isLoading = false
      })
    },
    onPickFile () {
      this.$refs.fileInput.click()
    },
    fileUpload: function (event) {
      let $this = this
      const files = event.target.files
      let filename = files[0].name // 只有一个文件
      if (filename.lastIndexOf('.') <= 0) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.message4)
        return
      }
      const fileReader = new FileReader() // 内置方法new FileReader()   读取文件
      fileReader.addEventListener('load', () => {
        this.imageUrl = fileReader.result
      })
      fileReader.readAsDataURL(files[0])
      event.preventDefault()
      var formData = new FormData()
      formData.append('file', files[0])
      this.isLoading2 = true

      tracemgrApi['supplierDistributionApiList'].fileUpload(formData).then(res => {
        if (res.data.result) {
          $this.success(this.$i18n.messages[this.$i18n.locale].traceMgr.UploadSucessFileIdIs)
          $this.loadCount = $this.loadCount + 1
          $this.isLoading2 = false
        } else {
          $this.faileFileId = res.data.faileFileId
          $this.error(res.data.errorMessage)
          $this.isLoading2 = false
        }
      }, res => {
        $this.isLoading2 = false
      })
      $this.isLoading2 = false
      this.$refs.fileInput.value = null
    },
    /**
     * 反馈文件下载
     */
    downLoadErrorFile () {
      let $this = this
      $this.showLoading = true
      fileApi.file.download({ keyId: $this.faileFileId }).then(res => {
        downFile(res)
        $this.showLoading = false
      }).catch(() => {
        $this.showLoading = false
      })
      // tracemgrApi['importPreDistributionOrderDialog'].downLoadErrorFile({
      //   filePath: this.errorMsgFileDir,
      //   fileName: this.errorMsgFileName
      // }, this.errorMsgFileName)
      // this.showLoading = false
    },
    save: function () {
      let $this = this
      var saveData = []

      for (var tmpInput in $this.inputModel) {
        var tmp = { 'keyId': '', 'applyReallocationFlag': 1, 'reallocationReason': '' }
        tmp.keyId = $this.inputModel[tmpInput].creditorAllocationId
        tmp.reallocationReason = $this.inputModel[tmpInput].reallocationReason
        tmp.applyReallocationFlag = $this.inputModel[tmpInput].applyReallocationFlag
        saveData.push(tmp)
      }
      if (saveData.length <= 0) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.saveMass)
        return
      }
      this.$confirm(this.$i18n.messages[this.$i18n.locale].traceMgr.message5, this.$i18n.messages[this.$i18n.locale].common.tip, {
        confirmButtonText: this.$i18n.messages[this.$i18n.locale].common.yes,
        cancelButtonText: this.$i18n.messages[this.$i18n.locale].common.no,
        type: 'warning'
      }).then(() => {
        $this.isLoading3 = true
        tracemgrApi['supplierDistributionApiList'].save(saveData).then(res => {
          $this.loadCount = $this.loadCount + 1
          $this.isLoading3 = false
          $this.inputModel = {}
        }, res => {
          $this.isLoading3 = false
          $this.inputModel = {}
        })
      }).catch(() => {
        $this.$message({
          type: 'info',
          message: this.$i18n.messages[this.$i18n.locale].traceMgr.message6
        })
      })
    }
  }
}
</script>
