<template>
  <div>
    <el-row :gutter="20">
      <el-col
        :xs="24"
        :lg="24"
        :sm="24"
        style="color:#787878;margin-bottom:20px"
        ><span>数据统计</span
        ><el-button
          v-has="'WORKORDER_ADMIN'"
          type="primary"
          target="blank"
          @click="toTj"
          style="border-radius:21px;margin-left:10px;margin-right:10px"
          >统计图表</el-button
        >
        <span v-has="'WORKORDER_ADMIN'">
          当前区域：<el-cascader
            ref="regionRef"
            class="filter-item"
            v-model="regionSearchVal"
            style="width:240px"
            :options="regions"
            :props="{ checkStrictly: true }"
            placeholder="行政区域"
            @change="handleRegionChange"
          />
        </span>
        <span v-has="'WORKORDER_ADMIN'">
          <el-button
            type="primary"
            style="border-radius:21px;margin-left:10px;margin-right:10px"
            @click="handleExport"
          >
            导出当前区域办结数据
          </el-button>
        </span>
        <span style="float:right"
          >更新时间：{{ new Date() | parseTime("{y}-{m}-{d} {h}:00:00") }}</span
        ></el-col
      >
      <el-col
        v-for="(value, key, index) in statisticalData"
        :key="index"
        :xs="12"
        :sm="12"
        :lg="key === 'all' ? 12 : 6"
      >
        <div
          class="countLayout"
          @click="key !== 'all' && showDetail(key)"
          :style="{ cursor: key !== 'all' && 'pointer' }"
        >
          <i :class="`countIcon icon_${index}`"></i>
          <span v-if="key === 'all'" style="font-size:24px"
            >累计服务量 ：<span
              style="color:#ff663d;font-size:49px;vertical-align: middle;"
              >{{ value }}</span
            ></span
          >
          <div
            v-else
            style="flex: 1;text-align: right;padding-right:51px;font-size:16px;"
          >
            <div style="margin-bottom:17px">{{ key }}</div>
            <div style="font-size:20px;color:#787878;">
              {{ formatUnit(key, value) }}
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title="dialogTitle" :visible.sync="dialogDetail" width="80%">
      <!-- <el-table :data="convenienceList"></el-table> -->
      <div class="convenienceList" v-loading="listLoading">
        <div
          v-for="(item, index) in convenienceList"
          :key="item.id"
          class="convenience_item"
          @click="
            $router.push({
              path: '/convenience/detail',
              query: { id: item.id }
            })
          "
        >
          <div class="convenience_item_title" style="flex:1">
            <i class="icon_list" />
            <div>
              <div class="cTitle">{{ item.eventType.eventName }}</div>
              <div class="createDate">
                {{ item.sponsor | sponsorFilter }}创建于{{
                  item.createDate | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
                }}
              </div>
            </div>
          </div>
          <div style="display:flex;flex:2;font-size:14px;color:#787878">
            <div style="flex:1">
              <p>流水号：{{ item.serialNumber }}</p>
              <p>
                阶段：{{ item.phase | phaseFilter }}
                <i
                  class="icon_timeout"
                  v-if="timers && timers[index].status !== null"
                ></i>
                <span style="color:#ff3000">{{
                  timers && timers[index].status === null
                    ? ""
                    : timers && timers[index].status
                    ? "已超时"
                    : "即将超时"
                }}</span>
              </p>
            </div>
            <div style="flex:1">
              <p>
                申办人：{{
                  item.residentInformation && item.residentInformation.name
                }}
              </p>
              <p>
                状态：<span style="color:#ff5a00">{{
                  item.statusList[0].status | statusFilter
                }}</span>
              </p>
            </div>
            <div style="flex:1">
              <p>
                受理人：{{
                  item.firstResponsiblePerson && item.firstResponsiblePerson.name
                }}
              </p>
            </div>
            <div
              style="flex:1;align-items: center;justify-items: center;display: flex;"
            >
              <div style="font-size:20px;color:#ff6918">
                <i class="icon_timer" />{{
                  (timers && timeFormat(timers[index].time)) || "00:00:00"
                }}
                <div>
                  <!-- <el-button
                    v-if="item.phase === 'PENDING_ORDER'"
                    style="margin-left:44px;font-size:14px;padding:7px 10px;width:70px;margin-top:12px"
                    type="primary"
                    size="mini"
                    @click.stop="handleUpdate(item, 5)"
                    >接单</el-button
                  > -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDetail = false">取 消</el-button>
        <!-- <el-button type="primary" @click="dialogDetail = false"
          >确 定</el-button
        > -->
      </span>
    </el-dialog>
    <el-dialog title="选择导出时间段" :visible.sync="dialogExport" width="20%">
      <el-date-picker
        v-model="dates"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="timestamp"
        @change="handleDateChange"
      >
      </el-date-picker>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogExport = false">取 消</el-button>
        <el-button type="primary" @click="exportExcel" :loading="exportLoading">确 定</el-button>
      </span>
    </el-dialog>
    <!-- handleExport -->
  </div>
</template>

<script>
import CountTo from "vue-count-to";
// import RegionSelect from "@/components/RegionSelect";
import { parseTime } from "@/utils";
import { getRegions } from "@/api/region";
import { statisticalData } from "@/api/statisticalData";
import { mapGetters } from "vuex";
import { listForData, leaderTVData } from "@/api/convenience";
import { isArray } from "@/utils/validate";

export default {
  data() {
    return {
      listQuery: {
        regionIds: undefined,
        residentInformationId: undefined,
        eventTypeId: undefined
      },
      excelListQuery: {
        isAll: true,
        regionIds: undefined,
        start: undefined,
        end: undefined
      },
      statisticalData: undefined,
      checkStrictly: false,
      regionSearchVal: undefined,
      // regionIds: undefined,
      regions: [],
      dialogDetail: false,
      dialogTitle: "提示",
      convenienceList: [],
      timers: undefined,
      timersInterval: undefined,
      listLoading: false,
      dialogExport: false,
      dates: undefined,
      // originRegion: undefined,
      exportLoading:false
    };
  },
  components: {
    CountTo
    // RegionSelect
  },
  filters: {
    sponsorFilter(status) {
      const statusMap = {
        SELF: "群众",
        STAFF: "工作人员"
      };
      return statusMap[status];
    },
    phaseFilter(status) {
      const statusMap = {
        PENDING_ORDER: "待接单",
        PREREQUISITES: "要件准备中",
        PROCESSING: "办理中",
        FINISH: "办结"
      };
      return statusMap[status];
    },
    statusFilter(status) {
      const statusMap = {
        MINE: "我处理",
        FORWARDED: "已转交",
        FORWARDED_APPLY: "转交超限审批中",
        SUBMIT_APPLY: "已提交审批",
        WAIT_APPLY: "待审核"
      };
      return statusMap[status];
    },
    typeFilter(status) {
      const statusMap = {
        1: "建立工单",
        2: "撤销工单",
        3: "沟通",
        4: "调整工单类别",
        5: "接单",
        6: "要件齐备",
        7: "办结",
        8: "转交超限审批提交",
        9: "转交超限审批撤销",
        10: "转交超限审批",
        11: "发起审批",
        12: "撤销审批",
        13: "审批操作",
        14: "转交"
      };
      return statusMap[status];
    }
  },
  computed: {
    ...mapGetters(["regionIds"])
  },
  created() {
    this.getStatisticalData();
    this.getRegions();
    this.regionSearchVal = this.regionIds;
    this.listQuery.regionIds = this.regionIds;
    this.excelListQuery.regionIds = this.regionIds;
  },
  methods: {
    // handleSetLineChartData(type) {
    //   this.$emit("handleSetLineChartData", type);
    // }
    getStatisticalData() {
      statisticalData(this.listQuery).then(res => {
        // this.statisticalData = {
        //   all: 318,
        //   平均办结时间: 61722,
        //   平均受理时间: 22349,
        //   未受理量: 0,
        //   未受理率: 0,
        //   按时受理量: 318,
        //   按时受理率: 1.0,
        //   超时受理量: 0,
        //   超时受理率: 0.0,
        //   按时办结量: 307,
        //   按时办结率: 1.0,
        //   超时办结量: 0,
        //   超时办结率: 0.0,
        //   未办结量: 11,
        //   未办结率: 0.0346,
        //   非常满意量: 274,
        //   非常满意率: 0.8925,
        //   满意量: 33,
        //   满意率: 0.1075,
        //   不满意量: 0,
        //   不满意率: 0.0
        // };
        this.statisticalData = res.d;
      });
    },
    formatUnit(key, value) {
      // console.log(key,value);
      let str = "";
      if (key.indexOf("率") != -1) {
        str = `${(value * 100).toFixed(2)}%`;
      } else if (key.indexOf("时间") != -1) {
        str = this.timeFormat(value);
      } else {
        str = value;
      }
      // console.log(str);
      return str;
    },
    timeFormat(timeStamp) {
      const timeStr = `${
        Math.floor(timeStamp / 3600) < 9
          ? "0" + Math.floor(timeStamp / 3600)
          : Math.floor(timeStamp / 3600)
      }:${
        Math.floor(((timeStamp % 86400) % 3600) / 60) < 9
          ? "0" + Math.floor(((timeStamp % 86400) % 3600) / 60)
          : Math.floor(((timeStamp % 86400) % 3600) / 60)
      }:${
        Math.floor(((timeStamp % 86400) % 3600) % 60) < 9
          ? "0" + Math.floor(((timeStamp % 86400) % 3600) % 60)
          : Math.floor(((timeStamp % 86400) % 3600) % 60)
      }`;
      return timeStr;
    },
    toTj() {
      window.open(
        // "http://localhost:9527/static/largeScreen/leaderForTv.html?regionIds="+this.regionIds
        `${process.env.VUE_APP_BASE_URL}static/largeScreen/leaderForTv.html?regionIds=${this.listQuery.regionIds}`
        //"http://new.rtmedia.myntv.cn/static/largeScreen/leaderForTv.html?regionIds=" + this.regionIds
      );
      // console.log(window);
    },
    getRegions() {
      getRegions().then(res => {
        const tempData = res.d;
        const countyArr = []; // 县,1
        tempData.map(county => {
          const countyObj = {
            value: county.root.id,
            label: county.root.name,
            disabled: !county.root.check,
            children: []
          };
          countyArr.push(countyObj);
          county.node.map(town => {
            const townObj = {
              value: town.root.id,
              label: town.root.name,
              disabled: !town.root.check,
              children: []
            };
            countyObj.children.push(townObj);
            town.node.map(country => {
              townObj.children.push({
                value: country.root.id,
                label: country.root.name,
                disabled: !country.root.check
              });
            });
          });
        });
        this.regions = countyArr;
      });
    },
    handleRegionChange(val) {
      // console.log(val);
      this.listQuery.regionIds = val.join(",");
      this.excelListQuery.regionIds = val.join(",");
      this.getStatisticalData();
    },
    showDetail(key) {
      this.convenienceList = undefined;
      this.listLoading = true;
      listForData({
        key,
        regionIds: this.listQuery.regionIds
      })
        .then(res => {
          this.listLoading = false;
          this.convenienceList = res.d.list;
          clearInterval(this.timersInterval);
          const tempData = res.d.list;
          const now = Date.parse(new Date()).toString() / 1000;
          // console.log(now);
          const arr = [];
          console.log(tempData);
          tempData.map((item, index) => {
            let msec = [];
            let obj = {};
            switch (item.phase) {
              case "PENDING_ORDER":
                // 待接单
                msec = now - item.createDate;
                obj = {
                  time: msec,
                  phase: item.phase,
                  status: null
                };
                arr.push(obj);
                break;
              case "PREREQUISITES":
                // 要件准备
                msec = now - item.createDate;
                obj = {
                  time: msec,
                  phase: item.phase,
                  status: null
                };
                arr.push(obj);
                break;
              case "PROCESSING":
                // 办理中
                msec = now - item.createDate;
                obj = {
                  time: msec,
                  phase: item.phase,
                  status: null
                };
                arr.push(obj);
                break;
              case "FINISH":
                msec =
                  item.acceptanceTime +
                  item.prerequisitesTime +
                  item.finishTime;
                obj = {
                  time: msec,
                  phase: item.phase,
                  status: null
                };
                arr.push(obj);
                // 办结
                break;
              default:
                break;
            }
          });
          if (arr.length > 0) {
            arr.map((item, index) => {
              if (item.phase !== "FINISH") {
                item.time++;
                if (this.convenienceList[index].phase === "PENDING_ORDER") {
                  if (item.status == null) {
                    if (item.time > 57600) {
                      item.status = false;
                      if (item.time >= 86400) {
                        item.status = true;
                      }
                    }
                  }
                }
                if (this.convenienceList[index].phase === "PROCESSING") {
                  if (item.status == null) {
                    // &&item.time<this.list[index].eventType.commitmentTimeLimit
                    if (
                      item.time >
                      this.convenienceList[index].eventType.timeoutReminder *
                        3600
                    ) {
                      item.status = false;
                      if (
                        item.time >=
                        this.convenienceList[index].eventType
                          .commitmentTimeLimit *
                          3600
                      ) {
                        item.status = true;
                      }
                    }
                  }
                }
              }
            });
          }
          this.timers = arr;

          this.timersInterval = setInterval(() => {
            if (this.convenienceList && arr.length > 0) {
              arr.map((item, index) => {
                if (item.phase !== "FINISH") {
                  item.time++;

                  if (this.convenienceList[index].phase === "PENDING_ORDER") {
                    if (item.status == null) {
                      if (item.time > 57600) {
                        item.status = false;
                        if (item.time >= 86400) {
                          item.status = true;
                        }
                      }
                    }
                  }
                  if (this.convenienceList[index].phase === "PROCESSING") {
                    if (item.status == null) {
                      // &&item.time<this.list[index].eventType.commitmentTimeLimit
                      if (
                        item.time >
                        this.convenienceList[index].eventType.timeoutReminder *
                          3600
                      ) {
                        item.status = false;
                        if (
                          item.time >=
                          this.convenienceList[index].eventType
                            .commitmentTimeLimit *
                            3600
                        ) {
                          item.status = true;
                        }
                      }
                    }
                  }
                }
              });
            }
            this.timers = arr;
          }, 1000);
        })
        .catch(error => {
          this.listLoading = false;
        });
      this.dialogTitle = key;
      this.dialogDetail = true;
    },
    handleExport() {
      this.dialogExport = true;
    },
    exportExcel() {
      const that = this;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = ["姓名", "办结数量", "未办结数量"];
        const filterVal = ["name", "num", "notFinishNum"];
        this.exportLoading = true
        leaderTVData(that.excelListQuery).then(res => {
          setTimeout(() => {
            this.exportLoading = false
          }, 3000);
          
          const data = that.formatJson(filterVal, res.d.leaderboard);
          // console.log(data);
          const selectRegionLabel = that.$refs['regionRef'].getCheckedNodes()[0].pathLabels.join(',')
          excel.export_json_to_excel({
            header: tHeader,
            data: data,
            // filename: `${that.regions[0].label}-${new Date(
            //   this.excelListQuery.start
            // )}-${new Date(this.excelListQuery.end)}-办事数量统计`
            filename: `${selectRegionLabel +
              "-" +
              (that.dates
                ? new Date(that.excelListQuery.start*1000).toLocaleDateString() +
                  "-" +
                  new Date(that.excelListQuery.end*1000).toLocaleDateString()
                : "") +
              "办事数量统计"}`
          });
        });
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          let value;
          if (j === "status") {
            value = this.$options.filters["statusFilter"](v[j]);
          } else {
            value = v[j];
          }
          // if (!value && value !== 0) value = "N/A";
          return value;
        })
      );
    },
    // dateFormatTime(date) {
    //   if (date != null) {
    //     this.listQuery.start = Date.parse(date[0]) / 1000;
    //     this.listQuery.end = Date.parse(date[1]) / 1000;
    //   } else {
    //     this.listQuery.start = undefined;
    //     this.listQuery.end = undefined;
    //   }
    // },
    handleDateChange(val) {
      // console.log(val);
      if (val != null) {
        this.excelListQuery.start = this.dates[0]/1000;
        this.excelListQuery.end = this.dates[1]/1000;
      } else {
        this.excelListQuery.start = undefined;
        this.excelListQuery.end = undefined;
      }
    },
    getRegionsText() {
      let tempLen;
      if (Array.isArray(this.regionSearchVal)) {
        tempLen = this.regionSearchVal.length;
      } else {
        tempLen = this.regionSearchVal.split(",").length;
      }
      // const tempLen = this.regionSearchVal.split(",").length;
      // console.log(tempLen);
      // this.regionSearchVal = [];
      // this.staffQuery.regionIds = this.regionIds;
      // switch (tempLen) {
      //   case 1:
      //     console.log(1);
      //     console.log(this.regions[tempLen-1].label);
      //     // this.regionSearchVal.push(this.regionIds, false);

      //     // console.log(this.regionSearchVal);
      //     break;
      //   case 2:
      //     console.log(2);
      //     console.log(this.regions[tempLen-1].label);
      //     // this.regionSearchVal.push(this.regionIds, false);
      //     // console.log(this.regionSearchVal);
      //     break;
      //   case 3:
      //     console.log(3);
      //     // this.regionSearchVal.push(this.regionIds);
      //     break;
      //   default:
      //     // this.regionSearchVal = [];
      //     break;
      // }
    }
  }
};
</script>

<style lang="scss" scoped>
.countLayout {
  background: #fff;
  margin-bottom: 18px;
  display: flex;
  align-items: center;
}
.countIcon {
  display: inline-block;
  background-size: cover !important;
  width: 60px;
  height: 60px;
  margin: 38px 38px 38px 55px;
  vertical-align: middle;
}
.icon_0 {
  background: url("./img/icon_0.png") no-repeat;
}
.icon_1 {
  background: url("./img/icon_1.png") no-repeat;
}
.icon_2 {
  background: url("./img/icon_2.png") no-repeat;
}
.icon_3 {
  background: url("./img/icon_3.png") no-repeat;
}
.icon_4 {
  background: url("./img/icon_3.png") no-repeat;
}
.icon_5 {
  background: url("./img/icon_4.png") no-repeat;
}
.icon_6 {
  background: url("./img/icon_4.png") no-repeat;
}
.icon_7 {
  background: url("./img/icon_5.png") no-repeat;
}
.icon_8 {
  background: url("./img/icon_5.png") no-repeat;
}
.icon_9 {
  background: url("./img/icon_6.png") no-repeat;
}
.icon_10 {
  background: url("./img/icon_6.png") no-repeat;
}
.icon_11 {
  background: url("./img/icon_7.png") no-repeat;
}
.icon_12 {
  background: url("./img/icon_7.png") no-repeat;
}
.icon_13 {
  background: url("./img/icon_8.png") no-repeat;
}
.icon_14 {
  background: url("./img/icon_8.png") no-repeat;
}
.icon_15 {
  background: url("./img/icon_9.png") no-repeat;
  width: 63px;
  height: 54px;
}
.icon_16 {
  background: url("./img/icon_9.png") no-repeat;
  width: 63px;
  height: 54px;
}
.icon_17 {
  background: url("./img/icon_10.png") no-repeat;
  width: 63px;
  height: 54px;
}
.icon_18 {
  background: url("./img/icon_10.png") no-repeat;
  width: 63px;
  height: 54px;
}
.icon_19 {
  background: url("./img/icon_11.png") no-repeat;
  width: 63px;
  height: 54px;
}
.icon_20 {
  background: url("./img/icon_11.png") no-repeat;
  width: 63px;
  height: 54px;
}
// .icon_21{
//   background:url('./img/icon_1.png')no-repeat;
// }
.numText {
  font-size: 20px;
  color: #787878;
  font-family: PingFang-SC-Regular;
  text-align: right;
}
.panel-group {
  margin-top: 18px;

  .card-panel-col {
    margin-bottom: 32px;
  }

  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
    border-color: rgba(0, 0, 0, 0.05);

    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }

      .icon-people {
        background: #40c9c6;
      }

      .icon-message {
        background: #36a3f7;
      }

      .icon-money {
        background: #f4516c;
      }

      .icon-shopping {
        background: #34bfa3;
      }
    }

    .icon-people {
      color: #40c9c6;
    }

    .icon-message {
      color: #36a3f7;
    }

    .icon-money {
      color: #f4516c;
    }

    .icon-shopping {
      color: #34bfa3;
    }

    .card-panel-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }

    .card-panel-icon {
      float: left;
      font-size: 48px;
    }

    .card-panel-description {
      float: right;
      font-weight: bold;
      margin: 26px;
      margin-left: 0px;

      .card-panel-text {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .card-panel-num {
        font-size: 20px;
      }
    }
  }
}

@media (max-width: 550px) {
  .card-panel-description {
    display: none;
  }

  .card-panel-icon-wrapper {
    float: none !important;
    width: 100%;
    height: 100%;
    margin: 0 !important;

    .svg-icon {
      display: block;
      margin: 14px auto !important;
      float: none !important;
    }
  }
}
// .el-dialog__body{
//   background: #f7fafd !important;
// }

.convenience_item {
  padding: 32px;
  margin-bottom: 10px;
  background-color: #f7fafd;
  border-radius: 4px;
  display: flex;
  cursor: pointer;
}
.convenience_item_title {
  display: flex;
  flex: 1;
  align-items: center;
  line-height: 25px;
}
.cTitle {
  font-size: 18px;
  color: #000000;
}
.convenience_item_title .createDate {
  color: #787878;
  font-size: 14px;
}
.icon_list {
  background: url("../../../convenience/img/icon_list.png") no-repeat;
  background-size: cover;
  display: inline-block;
  width: 52px;
  height: 51px;
  margin-right: 12px;
}
.icon_timer {
  background: url("../../../convenience/img/icon_timer.png") no-repeat;
  background-size: cover;
  display: inline-block;
  width: 18px;
  height: 18px;
  margin-right: 4px;
  vertical-align: baseline;
  margin-left: 24px;
}
</style>
