<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" @select="changeValue">
      </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"
                      :queryParas="queryParas" :sourceData.sync="formTableData.sourceData" :border="true" :stripe="true"
                      :loadCount.sync="loadCount" :columns="columns" :operateBtnLayout="operateBtnLayout" v-bind="elHeightObj">
            <template slot="groupName" slot-scope="{data}">
              <span v-if="!data.row.add">{{data.row.groupName}}</span>
              <el-input v-if="data.row.add" maxlength="8" v-model="saveData.groupName"/>
            </template>
            <template slot="factoringUserName" slot-scope="{data}">
              <span v-if="!data.row.add">{{data.row.factoringUserName}}</span>
              <select-factoring-commissioner v-if="data.row.add"  v-model="saveData.factoringUserId" @selectChanged="change"></select-factoring-commissioner>
            </template>
            <template slot="documentaryProportion" slot-scope="{data}">
              <span v-if="!data.row.add">{{data.row.documentaryProportion}}</span>
              <el-input-number v-if="data.row.add" :min="0" :max="100" type="number" v-model="saveData.documentaryProportion"/>
            </template>

            <template slot="abilityValue" slot-scope="{data}">
              <span v-if="!data.row.add">{{data.row.abilityValue}}</span>
              <el-input-number v-if="data.row.add" :min="0" :max="100" type="number" v-model="saveData.abilityValue"/>
            </template>
            <template slot="headButton">
              <el-row>
                <el-col :span="24" class="textRight">
                  <auth-button v-if="isManage" size="medium" type="primary" @click="add" :label="$t('common.create')" class="iconfont iconxinzeng"></auth-button>
                  <auth-button v-if="isManage" size="medium" type="primary" @click="handleExport" :label="$t('common.export')" class="iconfont icondaochu"></auth-button>
                </el-col>
              </el-row>
            </template>
            <el-table-column :label="$t('common.operate')" align="center" fixed="right" :width="150">
              <template slot-scope="scope">
                <el-col v-if="scope.row.add">
                  <el-tooltip class="item" effect="dark" :content="$t('common.save')" placement="top">
                    <el-button @click="save(scope.row)" circle size="mini" :class="'iconfont iconbaocun'">
                    </el-button>
                  </el-tooltip>
                  <el-tooltip class="item" effect="dark" :content="$t('approval.cancel')" placement="top">
                    <el-button @click="cancel(scope.row)" circle size="mini" :class="'iconfont iconquxiao'">
                    </el-button>
                  </el-tooltip>
                </el-col>
                <el-col v-else>
                  <el-tooltip class="item" effect="dark" :content="$t('common.history')" placement="top">
                    <el-button @click="history(scope.row)" circle size="mini" class="iconfont iconmore">
                    </el-button>
                  </el-tooltip>
                  <el-tooltip v-if="isManage" class="item" effect="dark" :content="$t('common.edit')" placement="top">
                    <el-button @click="edit(scope.row)" circle size="mini" class="iconfont iconbianji">
                    </el-button>
                  </el-tooltip>
                </el-col>
              </template>
            </el-table-column>
          </data-table>
        </el-form>
      </template>
    </up-down-layout>
    <person-modify-history-dialog ref="historyDialog" :visible.sync="isShowHistory" :creditor="creditorId" :editModel="editModel" :form="item"></person-modify-history-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 } from 'newepoch-components'
import DatePicker from '@/components/element/DatePick.vue'
import personModifyHistoryDialog from '@/components/tracemgr/supplierDistribution/personModifyHistoryDialog'
import EnterpriseOperationDifficulty from '@/components/element/EnterpriseOperationDifficulty'
import tracemgrApi from '@/api/tracemgrApi'
import ShiftCallTime from '@/components/element/ShiftCallTime'
import fileApi from '@/api/fileApi.js'
import { downFile } from '@/utils/devUtils'
export default {
  extends: new BasePage(),
  name: 'personList',
  mixins: [mixin],
  components: {
    authButton,
    searchForm,
    upDownLayout,
    SelectAddress,
    ShiftCallTime,
    format,
    DataTable,
    SelectCoreEnterprise,
    SelectCoreEnterpriseCascade,
    SelectFactoringCommissioner,
    personModifyHistoryDialog,
    EnterpriseOperationDifficulty,
    DatePicker
  },
  mounted () {
    this.handleFilter()
  },
  data: function () {
    return {
      editModel: '',
      // 履历弹框是否显示
      isShowHistory: false,
      styles: '',
      creditorId: '',
      buttonDisable: false,
      needComplete: true,
      currentTotal: 0,
      loadPage: 'getPage',
      loadCount: 0,
      operateBtnLayout: '',
      employeeNum: '10',
      isAdd: 0, // 0为取消状态，1为新增，2为编辑
      isSave: false,
      formTableData: {
        sourceData: []
      },
      queryParas: {
        pageIndex: 1,
        pageSize: 10,
        group: '',
        name: '',
        role: '',
        post: '',
        onJobStatus: '',
        enrollmentTime: '',
        regularTime: '',
        shiftCallTime: ''
      },

      item: {},
      showOperation: true,
      handleFlag: true,
      options: [],
      isManage: false, // 是否是经理角色
      saveData: { 'keyId': '', 'groupName': '', 'factoringUserId': '', 'factoringUserName': '', 'documentaryProportion': '', 'abilityValue': '' },
      componentList: [
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.group,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          value: 'groupName',
          componentName: 'el-input',
          labelWidth: '70px',
          slot: true
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].common.name,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          value: 'name',
          labelWidth: '100px',
          componentName: 'el-input'
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.roleName,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          value: 'roleIds',
          dictTypeCode: 'tracemgr_employee_role',
          componentName: 'SelectDictionary',
          store: this.$store,
          labelWidth: '100px',
          filterable: true,
          multiple: true
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.post,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          value: 'posts',
          dictTypeCode: 'tracemgr_employee_postion',
          componentName: 'SelectDictionary',
          store: this.$store,
          labelWidth: '71px',
          multiple: true
        },
        {
          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',
          labelWidth: '100px',
          filterable: true,
          store: this.$store
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.enrollmentTime,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          value: 'enrollmentTime',
          componentName: DatePicker,
          labelWidth: '100px',
          type: 'daterange',
          format: 'yyyy-MM-dd'
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.regularTime,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.selectInfo,
          value: 'regularTime',
          componentName: DatePicker,
          labelWidth: '70px',
          type: 'daterange',
          format: 'yyyy-MM-dd'
        },
        {
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.shiftCallTime,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.input,
          value: 'shiftCallTime',
          labelWidth: '100px',
          componentName: ShiftCallTime
        }
      ],
      columns: [
        {
          prop: 'groupName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.group,
          showOverflowTooltip: false,
          width: '150px',
          slot: true
        },
        {
          prop: 'factoringUserName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.factoringCommissioner,
          showOverflowTooltip: false,
          width: '150px',
          slot: true
        },
        {
          prop: 'roleName',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.roleName,
          showOverflowTooltip: true,
          width: '150px'
        },
        {
          prop: 'post',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.post,
          showOverflowTooltip: true,
          width: '150px'
        },
        {
          prop: 'jobStatus',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.onJobStatus,
          showOverflowTooltip: true,
          width: '150px',
          format: function (row) {
            if (row.jobStatus === 0 || row.jobStatus === '0') {
              return ''
            }
            return format.formatDict(row.jobStatus, 'tracemgr_employee_job_status')
          }
        },
        {
          prop: 'entryDate',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.enrollmentTime,
          showOverflowTooltip: true,
          width: '200px',
          format: function (row) {
            if (row.add) {
              return ''
            } else {
              let date = new Date(row.entryDate)
              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 r = y + '-' + MM + '-' + d
              if (r === '1900-01-01') return ''
              return r
            }
          }
        },
        {
          prop: 'positiveDate',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.regularTime,
          showOverflowTooltip: true,
          width: '200px',
          format: function (row) {
            if (row.add) {
              return ''
            } else {
              let date = new Date(row.positiveDate)
              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 r = y + '-' + MM + '-' + d
              if (r === '1900-01-01') return ''
              return r
            }
          }
        },
        {
          prop: 'transferInCallDate',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.shiftCallDate,
          showOverflowTooltip: true,
          width: '200px',
          format: function (row) {
            if (row.add) {
              return ''
            } else {
              let date = new Date(row.transferInCallDate)
              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 r = y + '-' + MM + '-' + d
              if (r === '1900-01-01') return ''
              return r
            }
          }
        },
        {
          prop: 'shiftCallTime',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.shiftCallTime,
          showOverflowTooltip: true,
          width: '150px',
          format: function (row) {
            if (row.add) {
              return ''
            } else {
              let date = new Date(row.transferInCallDate)
              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 r = y + '-' + MM + '-' + d
              if (r === '1900-01-01') return ''
              return row.shiftCallTime
            }
          }
        },
        {
          prop: 'documentaryProportion',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.documentaryProportion,
          showOverflowTooltip: false,
          width: '200px',
          slot: true
        },
        {
          prop: 'abilityValue',
          align: 'center',
          label: this.$i18n.messages[this.$i18n.locale].traceMgr.abilityValue,
          showOverflowTooltip: false,
          width: '200px',
          slot: true
        }
      ]
    }
  },
  computed: {
    api () {
      return tracemgrApi['personApiList']
    }
  },
  created: function () {
    tracemgrApi['supplierDistributionApiList'].getUserInfo('').then(res => {
      this.isManage = res.data.role === '4'
      this.isLoading = false
    }, res => {
      this.isLoading = false
    })
  },
  watch: {
  },
  methods: {
    clearParam () {
      this.queryParas = {
        pageIndex: 1,
        pageSize: 10,
        shiftCallTime: ['', '', '', '', '', '']
      }
    },
    history: function (row) {
      let $this = this
      // $this.item = Object.assign({}, row)
      $this.creditorId = row.keyId + ''
      this.$refs.historyDialog.searchData(row.keyId + '')
      $this.isShowHistory = true
    },
    handleExport: function () {
      let $this = this
      this.isLoading = true
      tracemgrApi['personApiList'].exportExcel($this.queryParas).then(res => {
        if (res.success) {
          fileApi.file.download({ keyId: res.data }).then(res => {
            downFile(res)
            $this.loading = false
          }).catch(() => {
            $this.loading = false
          })
        } else {
          $this.loading = false
          $this.error(this.$i18n.messages[this.$i18n.locale].ladingManageList.exportFaile)
        }
      }).catch(() => {
        $this.isLoading = false
      })
    },
    changeValue: function (val) {
      this.$set(this.queryParas, 'shiftCallTime', val)
    },
    edit: function (row) {
      let $this = this
      let editFlag = false
      if (this.isSave) {
        return $this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.isSaveError)
      }
      this.isSave = false
      if (this.isAdd === 2) {
        this.formTableData.sourceData.forEach(item => {
          if (item.add) {
            editFlag = true
          }
        })
      }
      if (editFlag) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.message1)
        return
      }
      this.formTableData.sourceData.forEach(function (el) {
        $this.$delete(el, 'add')
      })
      this.$set(row, 'add', true)
      this.isAdd = 2
      this.saveData.keyId = row.keyId
      this.saveData.groupName = row.groupName
      this.saveData.factoringUserId = row.factoringUserId
      this.saveData.factoringUserName = row.factoringUserName
      this.saveData.documentaryProportion = row.documentaryProportion
      this.saveData.abilityValue = row.abilityValue
      this.saveData.jobStatus = row.jobStatus
    },
    add: function () {
      let num = 0
      let editFlag = false
      this.isSave = true
      if (this.isAdd === 2) {
        this.formTableData.sourceData.forEach(item => {
          if (item.add) {
            editFlag = true
          }
        })
      }
      if (editFlag) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.message1)
        return
      }
      this.formTableData.sourceData.forEach(item => {
        if (item.add) {
          num++
        }
      })
      if (num > 0) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.message2)
        return
      }
      this.formTableData.sourceData.unshift({
        add: true
      })
      this.isAdd = 1
    },
    cancel: function (row) {
      let $this = this
      this.isSave = false
      if (this.isAdd === 1) {
        delete this.formTableData.sourceData[0]
      } else {
        this.formTableData.sourceData.forEach(function (el) {
          $this.$delete(el, 'add')
        })
      }
      this.isAdd = 0
      this.saveData = { 'keyId': '', 'groupName': '', 'factoringUserId': '', 'factoringUserName': '', 'documentaryProportion': '', 'abilityValue': '' }
    },

    change: function (val, name, row) {
      if (val !== '') {
        this.saveData.factoringUserId = row.userId
        this.saveData.factoringUserName = row.nickName
      }
    },
    save: function (row) {
      let $this = this
      console.log(this.saveData)
      this.isLoading = true
      this.isSave = false
      tracemgrApi['personApiList'].save(this.saveData).then(res => {
        $this.loadCount = $this.loadCount + 1
        $this.isLoading = false
        $this.isAdd = 0
        $this.saveData = { 'keyId': '', 'groupName': '', 'factoringUserId': '', 'factoringUserName': '', 'documentaryProportion': '', 'abilityValue': '' }
      }, res => {
        $this.isLoading = false
      })
    }
  }
}
</script>
