<!-- 成长轨迹图谱 -->
<template>
  <div>
    <Row align="middle" type="flex">
      <Col class-name="align-left" span="18">
        <DatePicker
          :clearable="false"
          :editable="false"
          :options="startControl"
          placeholder="起始日期"
          placement="bottom-start"
          style="width:150px"
          type="month"
          v-model="dateRangeStart"
        ></DatePicker>
        <span style="padding: 0 6px;">-</span>
        <DatePicker
          :clearable="false"
          :editable="false"
          :options="endControl"
          placeholder="截止日期"
          placement="bottom-start"
          style="width:150px"
          type="month"
          v-model="dateRangeEnd"
        ></DatePicker>
        <Select placeholder="个人" style="margin-left: 8px; width:150px" v-model="roleSelect">
          <Option value="checkSingle">个人</Option>
          <Option value="checkBoth">业务小组平均</Option>
        </Select>
        <Button
          :loading="searchLoading"
          @click="doInitSearch"
          style="margin-left: 6px;"
          type="primary"
          v-permission:list
        >查询</Button>
        <advancedSearch
          :autoLoad="isAdvanLoad"
          :clearable="isNoAgent"
          :orgType="otype"
          @invokeDoSearch="exeDosearch"
          @on-confirm="handleAdvanSearch"
          @on-select-admin-group="AdvanSearchGroup"
          @on-select-special-line="AdvanSearchLine"
          @on-select-sub-center="AdvanSearchCenter"
        ></advancedSearch>
      </Col>
      <Col class-name="align-right" span="6">
        <Poptip @on-ok="handleExport" class="align-left" confirm title="确定导出表格信息？">
          <Button :disabled="searchLoading" :loading="exportLoading" v-permission:export>导出</Button>
        </Poptip>
      </Col>
    </Row>
    <br />
    <Table :columns="columnsDaily" :data="dataList" :loading="searchLoading" border></Table>
    <Page
      :current.sync="searchForm.pageNum"
      :page-size="searchForm.pageSize"
      :total="total"
      @on-change="pageChange"
      class="mt-set16"
      show-total
      v-permission:list
    />

    <Modal
      :footer-hide="true"
      :mask-closable="false"
      :title="mapTitle + ' - ' + chartDate"
      :width="700"
      v-model="isShowAll"
    >
      <RadioGroup @on-change="viewMap" v-model="chartsItem" v-show="isShowPieChart">
        <Radio label="图1">综述</Radio>
        <Radio label="图2">详情</Radio>
      </RadioGroup>
      <div v-show="showChartAll">
        <h5 class="chart-title">{{ chartTitle }}</h5>
        <chart-radar
          :indicatorArray="indicatorNameArray"
          :realDataArray="indicatorValueArray"
          v-show="indicatorNameArray.length>0"
        ></chart-radar>
      </div>
      <div v-show="!showChartAll">
        <h5 class="chart-title">{{ chartTitle }}</h5>
        <chart-pie :datas="pieChartData" :date="chartDate"></chart-pie>
      </div>
    </Modal>
  </div>
</template>

<script>
import { ChartRadar, ChartPie } from '@/views/components/echarts'
import advancedSearch from '@/views/components/advanced-search'
import { downloadExcel } from '@lib/download'
import {
  differenceInMonths,
  format,
  subMonths,
  startOfMonth,
  endOfMonth
} from 'date-fns'
import WfmGrowupGroupDataAPI from '@api/common/wfmGrowupGroupData'
import WfmGrowupPersonDataAPI from '@api/common/wfmGrowupPersonData'
import configValue from '@conf/index'
import commonadvSearch from '@/mixin/commonadvSearch'
import advanceSearchClear from '@/mixin/advanceSearchClear'
import store from '@/store'

export default {
  name: 'trajectory-map',
  mixins: [commonadvSearch, advanceSearchClear],
  components: {
    advancedSearch,
    ChartRadar,
    ChartPie
  },
  data () {
    return {
      searchLoading: false,
      searchForm: {
        pageNum: 1,
        pageSize: this.$config.PAGE_SIZE,
        startTime: null,
        endTime: null
      },
      searchDateRange: null,
      total: 0,
      current: 0,
      exportInfo: {},
      exportLoading: false,
      chartDate: '',
      selectedRowId: '',
      dateRangeStart: '',
      dateRangeEnd: '',
      modalIndex: false,
      userType: '',
      roleSelect: 'checkSingle',
      isShowAll: false,
      isShowPieChart: false,
      showChartAll: true,
      chartsItem: '图1',
      chartTitle: '',
      mapTitle: '',
      dataList: [],
      startControl: {
        disabledDate: date => {
          return date && date.valueOf() > this.dateRangeEnd
        }
      },
      endControl: {
        disabledDate: date => {
          let endDate = new Date(this.dateRangeStart)
          let startDate = subMonths(endDate, 1)
          return date && date.valueOf() <= startDate.getTime()
        }
      },
      columnsDaily: [
        {
          title: '月份',
          key: 'dataMonth',
          width: 100
        },
        {
          title: '中心',
          key: 'usercenter',
          width: 80,
          render (h, params) {
            return h('div', params.row.map.usercenter)
          }
        },
        {
          title: '专线',
          key: 'userline',

          render (h, params) {
            return h('div', params.row.map.userline)
          }
        },
        {
          title: '业务小组',
          key: 'usergroupname',
          minWidth: 120,
          render (h, params) {
            return h('div', params.row.map.usergroupname)
          }
        },
        {
          title: '工作效率',
          key: 'efficiencyScore',

          render: (h, params) => {
            return h(
              'a',
              {
                style: {
                  marginRight: '5px',
                  textDecoration: 'underline'
                },
                on: {
                  click: () => {
                    this.show(
                      params.row,
                      configValue.EVALUATE_Map.efficiencyScore,
                      params.column.title
                    )
                  }
                }
              },
              params.row[params.column.key]
                ? params.row[params.column.key].toFixed(2)
                : null
            )
          }
        },
        {
          title: '知识技能',
          key: 'skillScore',

          render: (h, params) => {
            return h(
              'a',
              {
                style: {
                  marginRight: '5px',
                  textDecoration: 'underline'
                },
                on: {
                  click: () => {
                    this.show(
                      params.row,
                      configValue.EVALUATE_Map.skillScore,
                      params.column.title
                    )
                  }
                }
              },
              params.row[params.column.key]
                ? params.row[params.column.key].toFixed(2)
                : null
            )
          }
        },
        {
          title: '服务质量',
          key: 'qaScore',

          render: (h, params) => {
            return h(
              'a',
              {
                style: {
                  marginRight: '5px',
                  textDecoration: 'underline'
                },
                on: {
                  click: () => {
                    this.show(
                      params.row,
                      configValue.EVALUATE_Map.qaScore,
                      params.column.title
                    )
                  }
                }
              },
              params.row[params.column.key]
                ? params.row[params.column.key].toFixed(2)
                : null
            )
          }
        },
        {
          title: '风险控制',
          key: 'riskControlScore',

          render: (h, params) => {
            return h(
              'a',
              {
                style: {
                  marginRight: '5px',
                  textDecoration: 'underline'
                },
                on: {
                  click: () => {
                    this.show(
                      params.row,
                      configValue.EVALUATE_Map.riskControlScore,
                      params.column.title
                    )
                  }
                }
              },
              params.row[params.column.key]
                ? params.row[params.column.key].toFixed(2)
                : null
            )
          }
        },
        {
          title: '考勤情况',
          key: 'attendanceScore',

          render: (h, params) => {
            return h(
              'a',
              {
                style: {
                  marginRight: '5px',
                  textDecoration: 'underline'
                },
                on: {
                  click: () => {
                    this.show(
                      params.row,
                      configValue.EVALUATE_Map.attendanceScore,
                      params.column.title
                    )
                  }
                }
              },
              params.row[params.column.key]
                ? params.row[params.column.key].toFixed(2)
                : null
            )
          }
        },
        {
          title: '个人资历',
          key: 'qualificationScore',

          render: (h, params) => {
            return h(
              'a',
              {
                style: {
                  marginRight: '5px',
                  textDecoration: 'underline'
                },
                on: {
                  click: () => {
                    this.show(
                      params.row,
                      configValue.EVALUATE_Map.qualificationScore,
                      params.column.title
                    )
                  }
                }
              },
              params.row[params.column.key]
                ? params.row[params.column.key].toFixed(2)
                : null
            )
          }
        },

        {
          title: '技能图谱得分',
          key: 'overallScore',

          render: (h, params) => {
            return h(
              'a',
              {
                style: {
                  marginRight: '5px',
                  textDecoration: 'underline'
                },
                on: {
                  click: () => {
                    this.showAll(params.row, params.column.title)
                  }
                }
              },
              params.row[params.column.key]
                ? params.row[params.column.key].toFixed(2)
                : null
            )
          }
        }
      ],
      colUserName: {
        title: '座席',
        key: 'username',

        render (h, params) {
          return h(
            'div',
            params.row.username
            // params.row.username === undefined ? '无' : params.row.username
          )
        }
      },
      colUsercode: {
        title: '员工编号',
        key: 'usercode',
        width: 100
      },
      indicatorNameArray: [],
      indicatorValueArray: [],
      pieChartData: [],
      lastSearchState: 'checkBoth'
    }
  },
  mounted () {
    this.searchDateRange = new Date(store.state.app.systemTime)
    this.columnsDaily.splice(4, 0, this.colUsercode)
    this.columnsDaily.splice(4, 0, this.colUserName)
  },
  watch: {
    searchDateRange () {
      this.searchForm.startTime = startOfMonth(this.searchDateRange).getTime()
      this.searchForm.endTime = endOfMonth(this.searchDateRange).getTime()
    },
    dateRangeStart (newVal) {
      if (this.dateRangeStart) {
        this.searchForm.startTime = format(
          new Date(this.dateRangeStart),
          this.$config.MONTH_FORMAT
        )
      } else {
        this.searchForm.startTime = ''
      }
    },
    dateRangeEnd (newVal) {
      if (this.dateRangeEnd) {
        this.searchForm.endTime = format(
          new Date(this.dateRangeEnd),
          this.$config.MONTH_FORMAT
        )
      } else {
        this.searchForm.endTime = ''
      }
    }
  },
  created () {
    let endDate = subMonths(new Date(store.state.app.systemTime), 1)
    let startDate = subMonths(new Date(store.state.app.systemTime), 1)
    this.searchForm.endTime = format(endDate, this.$config.MONTH_FORMAT)
    this.searchForm.startTime = format(startDate, this.$config.MONTH_FORMAT)
    this.dateRangeStart = startDate
    this.dateRangeEnd = endDate
  },
  methods: {
    // 导出
    handleExport () {
      this.exportLoading = true
      console.log(this.userType)
      if (this.userType !== 'checkSingle') {
        if (this.dataList.length === 0) {
          this.exportLoading = false
          this.$Message.destroy()
          this.$Message.warning('请先查询数据')
        } else {
          this.exportLoading = true
          WfmGrowupGroupDataAPI.exportexcel({ ...this.exportInfo })
            .then(({ data, headers }) => {
              this.exportLoading = false
              let fileName = decodeURIComponent(
                headers['content-disposition']
                  .split(';')[1]
                  .split('filename=')[1]
              )
              downloadExcel(data, fileName)
            })
            .catch(err => {
              console.error('err: ', err)
              this.exportLoading = false
            })
        }
      } else {
        if (this.dataList.length === 0) {
          this.exportLoading = false
          this.$Message.destroy()
          this.$Message.warning('请先查询数据')
        } else {
          this.exportLoading = true
          WfmGrowupPersonDataAPI.exportexcel({ ...this.exportInfo })
            .then(({ data, headers }) => {
              this.exportLoading = false
              let fileName = decodeURIComponent(
                headers['content-disposition']
                  .split(';')[1]
                  .split('filename=')[1]
              )
              downloadExcel(data, fileName)
            })
            .catch(err => {
              console.error('err: ', err)
              this.exportLoading = false
            })
        }
      }
    },
    pageChange (pageNum) {
      this.searchForm.pageNum = pageNum
      this.doSearch()
    },
    // 表格操作-查看
    show (row, type, title) {
      this.$Message.loading({
        content: '正在加载',
        duration: 0
      })
      this.indicatorNameArray.length = 0
      this.indicatorValueArray.length = 0
      this.chartDate = row.dataMonth

      this.isShowPieChart = false
      this.showChartAll = true
      this.mapTitle = title
      if (this.roleSelect === 'checkSingle') {
        WfmGrowupPersonDataAPI.detail({
          growId: row.uuid,
          typecode: type
        }).then(({ data }) => {
          if (data.status === 'success') {
            this.setRadarChartData(data)
          } else {
            this.$Message.destroy()
            this.$Message.error(data.message)
          }
        })
      } else {
        WfmGrowupGroupDataAPI.detail({ growId: row.uuid, typecode: type }).then(
          ({ data }) => {
            if (data.status === 'success') {
              this.setRadarChartData(data)
            } else {
              this.$Message.destroy()
              this.$Message.error(data.message)
            }
          }
        )
      }
    },
    setRadarChartData (data) {
      this.indicatorValueArray = []
      this.indicatorNameArray = []
      if (!data.data) {
        return
      }
      data.data.forEach(element => {
        let indicatorName = element.map.itemName
        let indicatorValue = element.formulaScore
        if (indicatorName) {
          this.indicatorNameArray.push({
            name: indicatorName,
            max: element.map.topScore ? element.map.topScore : 100
          })
        }
        if (indicatorValue) {
          this.indicatorValueArray.push(indicatorValue.toFixed(2))
        }
      })

      if (
        this.indicatorNameArray.length !== 0 ||
        this.indicatorValueArray.length !== 0
      ) {
        this.isShowAll = true
        this.$Message.destroy()
      } else {
        this.$Message.destroy()
        this.$Message.warning('未查到数据')
        setTimeout(() => {
          this.$Message.destroy()
        }, 1000)
      }
    },
    showAll (row, title) {
      this.selectedRowId = row.uuid
      this.isShowPieChart = true
      this.isShowAll = true
      this.showChartAll = true
      this.chartsItem = '图1'
      this.indicatorNameArray.length = 0
      this.indicatorValueArray.length = 0
      this.chartDate = row.dataMonth
      this.mapTitle = title

      this.setRadarDataForOverAll()
    },
    setRadarDataForOverAll () {
      if (this.roleSelect === 'checkSingle') {
        WfmGrowupPersonDataAPI.view(this.selectedRowId).then(({ data }) => {
          if (data.status === 'success') {
            this.setRadarChartData(data)
          } else {
            this.$Message.destroy()
            this.error(data.message)
          }
        })
      } else {
        WfmGrowupGroupDataAPI.view(this.selectedRowId).then(({ data }) => {
          if (data.status === 'success') {
            this.setRadarChartData(data)
          } else {
            this.$Message.destroy()
            this.$Message.error(data.message)
          }
        })
      }
    },
    setPieChartData () {
      this.pieChartData = []
      this.$Message.loading({
        content: '正在加载',
        duration: 0
      })

      if (this.roleSelect === 'checkSingle') {
        WfmGrowupPersonDataAPI.detail({
          growId: this.selectedRowId,
          typecode: configValue.EVALUATE_Map.overallScore
        }).then(({ data }) => {
          if (data.status === 'success') {
            this.$Message.destroy()
            if (data.data.length === 0) {
              this.$Message.warning('未查到详情数据')
              setTimeout(() => {
                this.$Message.destroy()
              }, 1000)
              return
            }
            this.pieChartData = []
            data.data.forEach(element => {
              let indicatorName = element.map.itemName
              let indicatorValue = element.formulaScore
              if (indicatorName && indicatorName) {
                this.pieChartData.push({
                  value: indicatorValue ? indicatorValue.toFixed(2) : 0,
                  name: indicatorName + ' ' + indicatorValue.toFixed(2),
                  legendname: indicatorName
                })
              }
            })
          } else {
            this.$Message.destroy()
          }
        })
      } else {
        WfmGrowupGroupDataAPI.detail({
          growId: this.selectedRowId,
          typecode: configValue.EVALUATE_Map.overallScore
        }).then(({ data }) => {
          if (data.status === 'success') {
            this.$Message.destroy()
            if (data.data.length === 0) {
              this.$Message.warning('未查到详情数据')
              setTimeout(() => {
                this.$Message.destroy()
              }, 1000)
              return
            }
            this.pieChartData = []
            data.data.forEach(element => {
              let indicatorName = element.map.itemName
              let indicatorValue = element.formulaScore
              if (indicatorName && indicatorName) {
                this.pieChartData.push({
                  value: indicatorValue ? indicatorValue.toFixed(2) : 0,
                  name: indicatorName + ' ' + indicatorValue.toFixed(2),
                  legendname: indicatorName
                })
              }
            })
          } else {
            this.$Message.destroy()
          }
        })
      }
    },

    viewMap (label) {
      if (label === '图1') {
        this.showChartAll = true
        this.setRadarDataForOverAll()
      } else {
        this.showChartAll = false
        this.setPieChartData()
      }
    },
    doInitSearch () {
      this.searchForm.pageNum = 1
      this.doSearch()
    },
    // 查询结果
    doSearch () {
      if (this.stopSearch()) {
        this.dataList = []
        return
      }
      this.searchLoading = true
      this.$nextTick(() => {
        const dateRange = differenceInMonths(
          new Date(this.searchForm.endTime),
          new Date(this.searchForm.startTime)
        )
        if (dateRange > this.$config.DATE_RANGE_SIX_MONTH) {
          this.$Message.warning(
            `日期范围不能超过${this.$config.DATE_RANGE_SIX_MONTH}月`
          )
          this.searchLoading = false
        } else {
          this.dataList = []
          console.log(this.roleSelect)
          if (this.roleSelect === 'checkSingle') {
            this.userType = 'checkSingle'
            if (this.columnsDaily[4].title !== '座席') {
              this.columnsDaily.splice(4, 0, this.colUsercode)
              this.columnsDaily.splice(4, 0, this.colUserName)
            }
            WfmGrowupPersonDataAPI.viewList({ ...this.searchForm })
              .then(({ data }) => {
                if (data.status === 'success') {
                  this.searchForm.startTime = format(
                    new Date(this.dateRangeStart),
                    this.$config.MONTH_FORMAT
                  )
                  this.searchForm.endTime = format(
                    new Date(this.dateRangeEnd),
                    this.$config.MONTH_FORMAT
                  )
                  if (this.paramsAdvance) {
                    this.exportInfo.usercenter = this.removeAnnotation(
                      this.paramsAdvance.sc.id
                    )
                    if (this.paramsAdvance.sl) {
                      this.exportInfo.userline = this.removeAnnotation(
                        this.paramsAdvance.sl.id
                      )
                    }
                    if (this.paramsAdvance.ag) {
                      this.exportInfo.usergroupname = this.removeAnnotation(
                        this.paramsAdvance.ag.id
                      )
                    }
                  }
                  this.searchLoading = false
                  this.total = data.data.total
                  this.dataList = data.data.list
                } else {
                  // this.$Message.error(data.message)
                }
              })
              .catch(() => {
                this.searchLoading = false
              })
          } else {
            if (this.columnsDaily[4].title === '座席') {
              this.columnsDaily.splice(4, 2)
            }
            this.userType = 'checkBoth'
            WfmGrowupGroupDataAPI.viewList({ ...this.searchForm })
              .then(({ data }) => {
                if (data.status === 'success') {
                  this.searchLoading = false
                  this.total = data.data.total
                  this.dataList = data.data.list
                } else {
                  // this.$Message.error(data.message)
                }
              })
              .catch(() => {
                this.searchLoading = false
              })
          }
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.charts {
  margin: 0 auto;
  width: 100%;
  height: 300px;
}
// .chart-title {
//   margin: 0 auto 8px;
//   width: 100px;
//   text-align: center;
//   color: #17233d;
//   font-weight: 700;
//   font-size: 20px;
//   border-bottom: 3px solid #b50029;
// }
</style>
