<template>
  <div class="page_timeAll">
    <div class="cell clearfix">
      <!-- <el-select
        v-model="listQuery.value"
        placeholder="请选择"
        style="width:120px;margin-right:20px"
        @change="selectChange"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select> -->
      <label class="title">
        <span class="name">日期查询</span> :
      </label>
      <el-date-picker
        v-model="listQuery.start_time"
        prefix-icon="el-icon-date"
        @change="changeTime"
        :editable="false"
        style="width: 196px;"
        type="date"
        placeholder="选择日期时间"
        align="right"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        :picker-options="pickerOptions"
      ></el-date-picker>
      <span class>-</span>
      <el-date-picker
        v-model="listQuery.end_time"
        prefix-icon="el-icon-date"
        @change="changeEndTime"
        :editable="false"
        style="width: 196px;"
        type="date"
        placeholder="选择日期时间"
        align="right"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        :picker-options="pickerOptions"
      ></el-date-picker>
    </div>
    <div class="tableTitle">统计图</div>
    <div class="cell clearfix" style="margin:0;">
        <p class="point"></p>
        <p class="pointTitle">次</p>
      </div>
    <div>
      <line-chart :options="chart"></line-chart>
    </div>
    <div class="tableTitle">统计表</div>
    <div>
      <el-table :data="tableData" border style="width: 100%" :row-style="{ color: '#303133' }" :header-cell-style="{backgroundColor: 'rgb(245, 247, 250)',color: '#606266'}">
        <el-table-column
          fixed
          label="日期"
          width="100"
          property="date"
          align="center"
        ></el-table-column>

        <el-table-column
          :label="modeItem.name"
          property="number"
          align="center"
          min-width="100"
          v-for="(modeItem, index) in activeModes"
          :key="index"
        >
          <template slot-scope="scope">
            {{ scope.row.data[modeItem.id].number ? scope.row.data[modeItem.id].number : "" }}
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          label="总次数"
          width="80"
          property="total"
          align="center"
        ></el-table-column>
      </el-table>

      <el-pagination
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[20, 40, 60, 80,100]"
        :page-size="10"
        background
        style="margin-top:20px;"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import echarts from "echarts";
import LineChart from "../../components/LineChart";
import {geStatistics,getTreatlist} from "@/api/common/common"
export default {
  components: {
    LineChart
  },
  data() {
    return {
      options: [
        {
          value: 0,
          label: "全部"
        },
        {
          value: 1,
          label: "留治"
        },
        {
          value: 2,
          label: "转出"
        },
      ],
      chart: {
        tooltip: {},
        // legend: {
        //   data: ["次"],
        //   left: 0
        // },
        xAxis: {
          data: []
        },
        yAxis: {
          axisLabel: {
            formatter: "{value} %"
          },
          show: false
        },
        series: [
          {
            name: "次",
            type: "bar",
            data: [],
            barWidth: 30,
            label: {
              normal: {
                show: true,
                position: "top",
                formatter: "{c}次"
              }
            },
            //配置样式
            itemStyle: {
              //通常情况下：

              //每个柱子的颜色即为colorList数组里的每一项，如果柱子数目多于colorList的长度，则柱子颜色循环使用该数组
              normal: {
                color: function(params) {
                  //我这边就两个柱子，大体就两个柱子颜色渐变，所以数组只有两个值，多个颜色就多个值
                  var colorList = [
                    ["#A9E0F3", "#9FBDFC"],
                    ["#A9E0F3", "#9FBDFC"],
                    ["#A9E0F3", "#9FBDFC"],
                    ["#FFD7C0", "#FF9994"],
                    ["#FFD7C0", "#FF9994"],
                    ["#FFD7C0", "#FF9994"],
                    ["#D7C3FD", "#B3A8F7"],
                    ["#D7C3FD", "#B3A8F7"],
                    ["#D7C3FD", "#B3A8F7"]
                  ];

                  var index = params.dataIndex;
                  if (params.dataIndex >= colorList.length) {
                    index = params.dataIndex % colorList.length;
                  }

                  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: colorList[index][0] },
                    // { offset: 0.5, color: colorList[index][1] },
                    { offset: 1, color: colorList[index][1] }
                  ]);
                },
                barBorderRadius: [5, 5, 0, 0] //柱状角成椭圆形
              },

              //鼠标悬停时：
              emphasis: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.2)"
              }
            }
          }
        ]
      },
      modeOptions:[],
      total:0,
      listQuery: {
        start_time: "",
        end_time: "",
        page: 1,
        limit: 20,
        value: 0,
        mode_id:"",
      },
      tableData:[],
      modesData: {
        xAxis: [],
        series: []
      },
      pickerOptions: {
        disabledDate(time) {
          let threeMonths = new Date(new Date().setFullYear(new Date().getFullYear()-1)).getTime() - 24 * 3600 * 1000;
          return time.getTime() > Date.now() || time.getTime() < threeMonths;;
        }
      },
    };
  },
  methods: {
    changeTime(val) {
      var time = this.getTimestamp(val) - this.getTimestamp(this.listQuery.end_time);
      if (time > 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.listQuery.start_time = "";
      } else {
        this.geStatistics()
      }

    },
    changeEndTime(val) {
      var time =
        this.getTimestamp(val) - this.getTimestamp(this.listQuery.start_time);
      if (time < 0) {
        this.$message.error("结束时间不能小于开始时间");
        this.listQuery.end_time = "";
      } else {
        this.geStatistics()
      }
    },
    getTimestamp(time) {
      // 把时间日期转成时间戳
      return new Date(time).getTime() / 1000;
    },
    handleSizeChange(limit) {
      this.listQuery.limit = limit;
      this.geStatistics();
    },
    handleCurrentChange(page) {
      this.tableData = []
      this.listQuery.page = page;
      this.geStatistics();
    },
   selectChange(val){
     this.tableData=[]
     this.listQuery.value =val
     this.geStatistics()
     this.getlist()
   },
   getlist(){
      this.modesData.series = []
      this.modesData.xAxis = []
     getTreatlist(this.listQuery).then(response=>{
        if(response.data.state == 1){
          var ttd =  response.data.data.list
            var modeMap = {};
            var batotal = 0;
            for (const index in ttd) {
              if (ttd[index].mode_id == "0") {
                continue;
              }
              modeMap[ttd[index].mode_id] = ttd[index];
            }
            for (const key in this.modeOptions) {
              this.modesData.xAxis.push(this.modeOptions[key].name);
              if (key in modeMap) {
                this.modesData.series.push(parseInt(modeMap[key].number));
                batotal += parseInt(modeMap[key].number);
              } else {
                this.modesData.series.push(0);
              }
            }

          this.chart.series[0].data = this.modesData.series
          this.chart.xAxis.data = this.modesData.xAxis
         }
     })
   },
    geStatistics(){
      geStatistics(this.listQuery).then(response=>{
        if(response.data.state === 1){
          var statistics =  response.data.data.statistics
          var treatinfo = response.data.data.treatinfo
          this.total =  response.data.data.total
          let dataInfo = {}
           treatinfo.forEach((item, index) => {
             let { date } = item
             if (!dataInfo[date]) {
                dataInfo[date] = {
                   date,
                   child: [],
                 }
                }
            })
         let list = Object.values(dataInfo)
      
         list.map(item=>{
           for(let i=0;i<statistics.length;i++){
             if(item.date == statistics[i].date){
                item.child.push(statistics[i])
             }
           }
         })
         var dtd = []
         list.map(item=>{
           item.child.map(it=>{
              dtd.push(it)
           })
         })
          var dd = {};
          for (const index in dtd) {
            if (!(dtd[index].date in dd)) {
               dd[dtd[index].date] = {};
            }
            if (!(dtd[index].mode_id in dd[dtd[index].date]) && dtd[index].mode_id != "0") {
              dd[dtd[index].date][dtd[index].mode_id] = dtd[index];
            }
          }
          console.log("dd",dd)
          for (const key in dd) {
            var total = 0;
            for (const mkey in this.modeOptions) {
              if (mkey in dd[key]) {
                console.log("=====",mkey)
                console.log(this.modeOptions[mkey].name)
                dd[key][mkey].mode = this.modeOptions[mkey].name;
                var number = parseInt(dd[key][mkey].number);
                if (isNaN(number) || number == 0) {
                  dd[key][mkey].number = "";
                  number = 0;
                }
                total += number;
              } else {
                dd[key][mkey] = {
                  mode: this.modeOptions[mkey].name,
                  mode_id: mkey,
                  number: 0
                };
              }
            }
            this.tableData.push({ date: key, data: dd[key], total: total });
          }
        }
       })
    },
 
  },
  created(){
    this.modeOptions = this.$store.getters.treatment_mode;
    var nowDate = new Date();
    var nowYear = nowDate.getFullYear();
    var nowMonth = nowDate.getMonth() + 1;
    var nowDay = nowDate.getDate();
    this.listQuery.end_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
    nowDate.setMonth(nowDate.getMonth() - 3);
    nowYear = nowDate.getFullYear();
    nowMonth = nowDate.getMonth() + 1;
    nowDay = nowDate.getDate();
    this.listQuery.start_time =
      nowYear +
      "-" +
      (nowMonth < 10 ? "0" + nowMonth : nowMonth) +
      "-" +
      (nowDay < 10 ? "0" + nowDay : nowDay);
      //获取柱状图数据
      this.getlist()
      //获取统计列表数据
      this.geStatistics()
  },
  computed: {
    activeModes: function() {
      var modes = [];
      for (const key in this.modeOptions) {
        if (this.listQuery.mode_id == key || this.listQuery.mode_id == "") {
          modes.push(this.modeOptions[key]);
        }
      }

      return modes;

    }
  },
};
</script>

<style lang="scss" scoped>
.tableTitle {
  font-size: 16px;
  color: #000;
  font-weight: bold;
  margin-bottom: 10px;
}
.point {
  width: 13px;
  height: 13px;
  background: linear-gradient(
    0deg,
    rgba(169, 224, 243, 1),
    rgba(159, 189, 252, 1)
  );
  border-radius: 7px;
  margin-right: 8px;
}
.pointTitle {
  font-size: 13px;
}
</style>

<style lang="scss">
.page_timeAll {
  .cell {
    text-align: center;
  }
  .el-table{
    ::-webkit-scrollbar{
      height: 15px;
    }
  }
}
</style>
