<template>
  <div>
    <div>
      <div :class="$style.box" bordered>
        <div :class="$style.opt">
          <p>关键用户待办情况统计</p>
          <span>
            <a-radio-group
              v-model="radioVal"
              button-style="solid"
              :class="$style.radio"
              @change="initData(radioVal)"
            >
              <a-radio-button value="1">当天</a-radio-button>
              <a-radio-button value="3">近三天</a-radio-button>
              <a-radio-button value="5">近五天</a-radio-button>
              <a-radio-button value="7">近一周</a-radio-button>
            </a-radio-group>

            <a-icon
              v-if="isShow"
              type="ellipsis"
              :class="[$style.icon, $style.iconhead]"
              @click="showmore"
            />
            <a-icon type="sync" :class="[$style.icon, $style.iconhead]" @click="reload" />
            <a-icon type="download" :class="[$style.icon, $style.iconhead]" @click="downloadData" />
          </span>
        </div>
        <div :class="$style.customwrap">
          <a-collapse
            :active-key="activeKey"
            :ghost="true"
            :show-arrow="false"
            :bordered="false"
            :class="$style.customstyle"
          >
            <a-collapse-panel v-for="item in todolist" :key="item.index">
              <template slot="header"
                ><a-row>
                  <a-col :span="3" :class="$style.listcolor">{{ item.name }}</a-col>
                  <a-col :span="5"
                    ><span :class="$style.listlabel">账号：</span>{{ item.account }}</a-col
                  >
                  <a-col :span="4"
                    ><span :class="$style.listlabel">新到待办：</span>{{ item.TODOCREATE }}</a-col
                  >
                  <a-col :span="4"
                    ><span :class="$style.listlabel">待办处理：</span>{{ item.TODODEL }}</a-col
                  >
                  <a-col :span="3" :class="$style.right"
                    ><span :class="[$style.listlabel, $style.avgtime]">平均时长</span></a-col
                  >
                  <a-col :class="$style.times" :span="5" flex="1"
                    ><li
                      ><a-icon type="desktop" :class="[$style.icon, $style.dblist]" />{{
                        item.avg_Computer
                      }}</li
                    ><li><a-icon type="mobile" :class="$style.icon" />{{ item.avg_Mobile }}</li>
                  </a-col>
                </a-row></template
              >
              <div :class="$style.customitem"
                ><a-row>
                  <a-list-item v-for="(i, index) in item.items" :key="i.intId" :class="$style.child"
                    ><a-col :span="13" :class="$style.dbtext" :title="i.title" :offset="1"
                      ><span>{{ index + 1 }}、{{ i.title }}</span></a-col
                    >
                    <a-col :class="[$style.dbtext, $style.app]" :title="i.appName">{{
                      i.appName
                    }}</a-col>
                    <a-col :class="$style.times" justify="end" :span="5"
                      ><li><a-icon type="desktop" :class="$style.icon" />{{ i.Computer }}</li
                      ><li><a-icon type="mobile" :class="$style.icon" />{{ i.Mobile }}</li>
                    </a-col>
                  </a-list-item>
                </a-row>
              </div>
            </a-collapse-panel>
          </a-collapse>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import moment from 'moment'
import components from './_import-components/xm-user-todolist-import'
import TrackService from './track-service'

export default {
  name: 'XmUserTodolist',
  metaInfo: {
    title: 'UserTodolist',
  },
  components,
  data() {
    return {
      radioVal: '1',
      activeKey: ['0', '1', '2'],
      todolist: [],
      isShow: true,
      exportdata: [],
      mergeArr: [],
      timedata: '',
    }
  },
  created() {
    this.initData(this.radioVal)
    if (window.location.href.includes('show')) {
      this.isShow = false
    }
    this.radioVal = this.$route.query.radioVal ? this.$route.query.radioVal.toString() : '1'
  },
  methods: {
    initData(days) {
      this.getdata(days)
      this.getTime(days)
    },
    getTime(val) {
      val = Number(val)
      const DateStr = new Date()
      const TimeDays = 1000 * 60 * 60 * 24
      const newFormat = 'YYYY-MM-DD'
      // 当前时间戳
      const nowTime = DateStr.getTime()
      let prevTime
      if (val === 1) {
        prevTime = nowTime
        this.timedata = moment(prevTime).format(newFormat)
      } else {
        prevTime = nowTime - TimeDays * val
        this.timedata =
          moment(prevTime).format(newFormat) + '至' + moment(nowTime).format(newFormat)
      }
    },
    getdata(days) {
      const params = {
        days: days,
      }
      TrackService.getUserTodo(params)
        .then((res) => {
          if (res.data.length > 0) {
            this.todolist = res.data
            this.todolist.map((item, index) => {
              item.items.map((item) => {
                if (item.Computer !== null || isNaN(item.Computer)) {
                  item.Computer = (item.Computer / 1000).toFixed(1) + 's'
                } else {
                  item.Computer = '--'
                }
                if (item.Mobile !== null || isNaN(item.Mobile)) {
                  item.Mobile = (item.Mobile / 1000).toFixed(1) + 's'
                } else if (item.Mobile === undefined) {
                  item.Mobile = '--'
                } else {
                  item.Mobile = '--'
                }
              })
              if (item.avg_Computer !== null || isNaN(item.avg_Computer)) {
                item.avg_Computer = (item.avg_Computer / 1000).toFixed(1) + 's'
              } else {
                item.avg_Computer = '--'
              }
              if (item.avg_Mobile !== null || isNaN(item.avg_Mobile)) {
                item.avg_Mobile = (item.avg_Mobile / 1000).toFixed(1) + 's'
              } else {
                item.avg_Mobile = '--'
              }
            })
          }
        })
        .catch((e) => {})
      // 因为excel中数字类型默认居右对齐，所以转为字符串让表格数据统一居左
      this.exportdata = []
      this.todolist.map((item, index) => {
        Object.keys(item).forEach((i) => {
          if (typeof item[i] === 'number') {
            item[i] = item[i].toString()
          }
        })
        const parentobj = { ...item }
        if (item.items.length > 0) {
          delete parentobj.items
          const alldata = item.items.map((item) => {
            return { ...parentobj, ...item }
          })
          this.exportdata.push(alldata)
        } else {
          this.exportdata.push(parentobj)
        }
      })
      this.exportdata = this.exportdata.flat()
      // 合并单元格
      const repeatArr = [{ s: { r: 1, c: 8 }, e: { r: 1, c: 9 } }]
      for (let i = 0; i < this.exportdata.length - 1; i++) {
        const item = this.exportdata[i]
        if (this.exportdata[i + 1].account === item.account) {
          const end = i + 1
          // 需要合并的列
          const mergeIndex = [0, 1, 2, 3, 8, 9]
          mergeIndex.map((item) => {
            const repeatObj = {}
            repeatObj.s = { r: i + 3, c: item }
            repeatObj.e = { r: end + 3, c: item }
            repeatArr.push(repeatObj)
          })
        }
      }
      this.mergeArr = [...repeatArr]
    },
    showmore() {
      const routeUrl = this.$router.resolve({
        path: '/xm-todolist-detail?show',
        query: { radioVal: this.radioVal },
      })
      window.open(routeUrl.href, '_blank')
    },
    downloadData() {
      this.exportJsonDataToExcel()
    },
    exportJsonDataToExcel() {
      let sheet = {}
      const headerA = '关键用户待办情况统计'
      const headerB = '统计日期:' + this.timedata
      let sheetlist = this.exportdata.map((item, index) => {
        return {
          姓名: item.name,
          账号: item.account,
          新到代办数量: item.TODOCREATE,
          待办处理数量: item.TODODEL,
          处理待办名称: item.title,
          待办应用: item.appName,
          PC端打开时长: item.Computer,
          移动端打开时长: item.Mobile,
          PC端平均打开时长: item.avg_Computer,
          移动端平均打开时长: item.avg_Mobile,
        }
      })
      sheetlist = [...sheetlist]
      sheet = XLSX.utils.json_to_sheet(sheetlist, { origin: { r: 2, c: 0 } })
      const colWidth = []
      const colNames = Object.keys(sheetlist[0])
      // 遍历行
      sheetlist.forEach((row) => {
        // 遍历列
        let index = 0
        for (const key in row) {
          if (colWidth[index] == null) colWidth[index] = []
          // 计算每列数据的长度
          colWidth[index].push(this.getWidth(row[key]))
          index++
        }
      })
      sheet['!cols'] = []
      // 每一列取最大值最为列宽
      colWidth.forEach((widths, index) => {
        // 计算列头的宽度
        widths.push(this.getWidth(colNames[index]))
        // 设置最大值为列宽
        sheet['!cols'].push({ wch: Math.max(...widths) })
      })
      sheet.E1 = {
        v: headerA,
        t: 's',
      }
      sheet.I2 = {
        v: headerB,
        t: 's',
      }
      sheet['!merges'] = this.mergeArr
      const workBook = {
        SheetNames: ['eee'],
        Sheets: {
          eee: sheet,
        },
      }
      XLSX.writeFile(workBook, `关键用户待办情况统计.xlsx`, {
        bookType: 'xlsx',
      })
    },
    getWidth(value) {
      // 判断是否为null或undefined
      if (value == null) {
        return 10
      } else if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
        // 判断是否包含中文
        let length = value.toString().length * 2.4
        if (length > 60) {
          length = length - 40
        }
        return length
      } else {
        return value.toString().length * 1.2
      }
    },
    reload() {
      this.initData(this.radioVal)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.box {
  position: absolute;
  width: 100%;
  height: 84%;
  padding-right: 5px;
  padding-left: 30px;
  margin-top: 5px;
  color: $card-background;
  -ms-overflow-style: none;
  p {
    margin-bottom: 0;
    font-size: $padding-lg;
  }
  .opt {
    display: flex;
    justify-content: space-between;
    padding: 0 10px 5px 15px;
  }
  .radio {
    padding-top: 4px;
    margin-right: 5px;
  }
  :global(.ant-collapse-content-box) {
    padding: 0;
  }
}
.customwrap {
  height: 100%;
  overflow: scroll;
}
.customstyle {
  margin-top: 10px;
  overflow: hidden;
  color: $alert-error-bg-color;
  background: #0b3787;
  border: 0;
  border-radius: 0;
  :global(.ant-collapse-item) {
    color: $alert-error-bg-color;
    border-bottom: 2px solid #01267b;
    :global(.ant-collapse-header) {
      color: $alert-error-bg-color;
    }
    :global(.ant-collapse-content) {
      color: $alert-error-bg-color;
    }
  }
  .listcolor {
    color: rgba(255, 255, 255, 0.9);
  }
  .listlabel {
    float: left;
    color: rgba(255, 255, 255, 0.7);
  }
  .avgtime {
    float: right;
  }
  .customitem {
    color: rgba(255, 255, 255, 0.9);
    background-color: #01267b;
    .child {
      border-bottom: 1px solid #ffffff17;
    }
    :global(.ant-list-item) {
      justify-content: space-around;
      padding: 12px 0;
    }
    :global(.ant-list-item):last-child {
      border: 0;
    }
    .app {
      width: 115px;
    }
  }
}
.times {
  white-space: nowrap;
  li {
    flex: 1;
    float: left;
    width: 58px;
    margin-right: 10px;
  }
  li:nth-child(3) {
    margin-right: 0;
  }
}
.icon {
  margin-right: 5px;
}
.iconhead {
  margin-right: 10px;
  font-size: $switch-height;
}
.dbtext {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.right {
  padding-right: 5px;
  text-align: right;
}
</style>
