<template>
  <div class="ele-body">
    <el-row :gutter="15">
      <el-col :span="16" style="height: calc(57% - 51px)">
        <div
          class=""
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
          "
        >
          <el-radio-group v-model="form.timeType" @change="timeTypeChange">
            <el-radio-button label="1">企业</el-radio-button>
            <el-radio-button label="2">工厂</el-radio-button>
            <!-- <el-radio-button label="3">班组</el-radio-button>
          <el-radio-button label="4">产线</el-radio-button> -->
          </el-radio-group>
          <div>
            <el-select
              v-if="form.timeType === '2'"
              v-model="params.factoryId"
              filterable
              placeholder="请选择工厂"
              size="mini"
              style="margin-right: 20px"
            >
              <el-option
                v-for="item in factoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <el-date-picker
              v-model="params.date"
              type="monthrange"
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              size="mini"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </div>
        </div>
        <div style="height: 20%" class="item">
          <div
            v-for="(item, index) in arr"
            :key="index"
            :style="{ color: item.color }"
          >
            <img :src="item.imgUrl" />
            <div>
              <span>
                {{ item.name }}
              </span>
              <span>
                {{ item.num }}
                <span>{{ item.unit }}</span>
              </span>
            </div>
          </div>
        </div>
        <el-card class="box-card" style="height: calc(80% - 15px)">
          <div slot="header" class="clearfix">
            <span>工单完成统计</span>
          </div>
          <v-chart ref="barRef" style="height: 100%" :option="barOption" />
        </el-card>
      </el-col>
      <el-col :span="8" style="height: 57%">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>不良品分布图</span>
          </div>
          <v-chart ref="pieRef" style="height: 100%" :option="pieOptions" />
        </el-card>
      </el-col>
      <el-col :span="24" style="height: 43%; margin-top: 15px">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>工单进度执行跟踪</span>
          </div>
          <ele-pro-table
            ref="table"
            height="calc(100%)"
            :columns="columns"
            :datasource="datasource"
            :toolbar="false"
            :needPage="false"
          >
          </ele-pro-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
  import dictMixins from '@/mixins/dictMixins';
  import { pieOption, barOption, columns, pieOptions } from './data';
  import { use } from 'echarts/core';
  import { CanvasRenderer } from 'echarts/renderers';
  import { BarChart, PieChart, LineChart } from 'echarts/charts';
  import {
    GridComponent,
    TooltipComponent,
    LegendComponent
  } from 'echarts/components';
  import VChart from 'vue-echarts';
  import { echartsMixin } from '@/utils/echarts-mixin';
  import {
    getCount,
    getCompletionCount,
    getOrderList,
    queryProportionDefectiveTypes
  } from '@/api/mes/index';

  import { getAllFactory } from '@/api/aps/index.js';

  // 按需加载 echarts
  use([
    CanvasRenderer,
    BarChart,
    PieChart,
    GridComponent,
    TooltipComponent,
    LegendComponent,
    LineChart
  ]);
  export default {
    mixins: [dictMixins, echartsMixin(['pieRef', 'barRef'])],
    components: { VChart },
    data() {
      return {
        columns,
        arr: [
          {
            name: '生产总数',
            num: '',
            imgUrl: require('../../assets/Group1.png'),
            unit: ''
          },
          {
            name: '待生产数量',
            num: '',
            imgUrl: require('../../assets/Group2.png'),
            unit: ''
          },
          {
            name: '已完成数量',
            num: '',
            imgUrl: require('../../assets/Group3.png'),
            unit: ''
          },
          {
            name: '生产中数量',
            num: '',
            imgUrl: require('../../assets/Group4.png'),
            unit: '',
            color: '#f97876'
          },
          {
            name: '已延期',
            num: '',
            imgUrl: require('../../assets/Group2.png'),
            unit: ''
          }
        ],

        pieOption: {},
        barOption: {},
        pieOptions: {},
        form: {
          finishTime: '',
          timeType: '1'
        },
        params: {
          // 工厂id
          factoryId: '',
          // 时间
          date: '',
          createTimeStart: '',
          createTimeEnd: ''
        },
        // 工厂列表
        factoryList: [],
        pickerOptions: {
          shortcuts: [
            {
              text: '本月',
              onClick(picker) {
                picker.$emit('pick', [new Date(), new Date()]);
              }
            },
            {
              text: '今年至今',
              onClick(picker) {
                const end = new Date();
                const start = new Date(new Date().getFullYear(), 0);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '最近六个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setMonth(start.getMonth() - 6);
                picker.$emit('pick', [start, end]);
              }
            }
          ]
        }
      };
    },
    watch: {
      params: {
        deep: true,
        handler(newVal) {
          // 处理参数变化 根据date同步createTimeStart和createTimeEnd
          if (newVal.date && newVal.date.length === 2) {
            this.params.createTimeStart = this.$util.toDateString(
              newVal.date[0],
              'yyyy-MM'
            );
            this.params.createTimeEnd = this.$util.toDateString(
              newVal.date[1],
              'yyyy-MM'
            );
          } else {
            this.params.createTimeStart = '';
            this.params.createTimeEnd = '';
          }

          this.getCount();
          this.getCompletionCount();
          this.proportion();
          this.$nextTick(() => {
            this.$refs.table.reload();
          });
        }
      }
    },
    created() {
      // this.pieOption = pieOption([
      //   { value: 40, name: '  外观检测' },
      //   { value: 30, name: '  尺寸检测' },
      //   { value: 15, name: '  性能检测' },
      //   { value: 10, name: '  密度检测' },
      //   { value: 5, name: '  重量检测' }
      // ]);

      // 设置params.date 为今年的开始和结束月份
      const currentYear = new Date().getFullYear();
      const startOfYear = new Date(currentYear, 0, 1); // 一月一日
      const endOfYear = new Date(currentYear, 11, 31); // 十二月三十一日
      this.params.date = [startOfYear, endOfYear];
      this.params.createTimeStart = this.$util.toDateString(
        startOfYear,
        'yyyy-MM'
      );
      this.params.createTimeEnd = this.$util.toDateString(endOfYear, 'yyyy-MM');

      this.getCount();
      this.getCompletionCount();
      this.proportion();
    },
    mounted() {
      this.getFactoryList();
      setTimeout(() => {
        this.$refs.barRef.resize();
        this.$refs.pieRef.resize();
      }, 300);
    },
    methods: {
      async getFactoryList() {
        const res = await getAllFactory();
        this.factoryList = res;
      },
      async proportion() {
        const res = await queryProportionDefectiveTypes(
          `?factoryId=${this.params.factoryId || ''}&createTimeStart=${
            this.params.createTimeStart
          }&createTimeEnd=${this.params.createTimeEnd}`
        );
        let list = res.map((el) => {
          return {
            value: el.unQualifiedNumber,
            name: el.categoryLevelClassName
          };
        });
        this.pieOptions = pieOptions(list);
      },
      datasource({ page, where, limit }) {
        return getOrderList({
          ...where,
          pageNum: page,
          size: limit,
          createTimeStart: this.params.createTimeStart,
          createTimeEnd: this.params.createTimeEnd,
          factoryId: this.params.factoryId || null
        });
      },
      timeTypeChange() {
        // 重置工厂选择
        this.params.factoryId = '';
      },
      //首页统计
      async getCount() {
        let rest = await getCount({
          factoryId: this.params.factoryId || null,
          createTimeStart: this.params.createTimeStart,
          createTimeEnd: this.params.createTimeEnd
        });
        this.arr.forEach((item, index) => {
          if (item.name === '生产总数') {
            item.num = rest.formingNum ? Number(rest.formingNum).toFixed(2) : 0;
          } else if (item.name === '待生产数量') {
            item.num = rest.pendingProductionCount
              ? Number(rest.pendingProductionCount).toFixed(2)
              : 0;
          } else if (item.name === '已完成数量') {
            item.num = rest.formedNum ? Number(rest.formedNum).toFixed(2) : 0;
          } else if (item.name === '生产中数量') {
            item.num = rest.inProgressWorkOrderCount
              ? Number(rest.inProgressWorkOrderCount).toFixed(2)
              : 0;
          } else if (item.name === '已延期') {
            item.num = rest.postponeCount
              ? Number(rest.postponeCount).toFixed(2)
              : 0;
          }
        });
        // console.log(rest, 'rest');
      },

      //工单完成统计
      async getCompletionCount() {
        let params = {
          createTimeStart: this.params.createTimeStart,
          createTimeEnd: this.params.createTimeEnd,
          factoryId: this.params.factoryId || null
        };
        let rest = await getCompletionCount(params);
        let inWarehouseCountList = []; //入库数量
        let inProductCountList = []; //在制工单数
        let xAxisData = []; //X轴数据

        rest.forEach((item) => {
          inWarehouseCountList.push(item.inWarehouseCount);
          inProductCountList.push(item.inProductCountList);
          xAxisData.push(item.inProductDate);
        });

        this.barOption = barOption(
          [
            {
              name: '工单入库数量',
              barWidth: '25%',
              data: inWarehouseCountList,
              type: 'bar',
              yAxisIndex: 0 // 使用第一个Y轴
            },
            {
              name: '工单数',
              symbolSize: 10,
              data: inProductCountList,
              type: 'line',
              smooth: true,
              itemStyle: {
                color: '#ffab08'
              }
            }
          ],
          {
            xAxis: {
              type: 'category',
              data: xAxisData,
              axisLabel: {
                fontSize: window.innerHeight * 0.012
              }
            }
          }
        );
        console.log('this.barOption', inWarehouseCountList, inProductCountList);
      }
    }
  };
</script>
<style lang="scss" scoped>
  .clearfix {
    font-size: 0.7vw;

    > span {
      font-weight: bold;
    }
    :deep(.el-radio-button__inner) {
      font-size: 0.7vw;
    }
  }
  .ele-body {
    height: calc(100vh - 111px);
    > .el-row {
      height: 100%;
    }
    .el-card {
      height: 100%;
      :deep(.el-card__body) {
        padding: 0.3vw;
      }
      :deep(.el-card__header) {
        padding: 0.8vw;
      }
      :deep(.el-card__body) {
        height: calc(100% - 1.6vw - 39px);
      }
      :deep(.ele-pro-table) {
        height: 99%;
      }
      :deep(.el-table) {
        font-size: 0.65vw;
      }
    }
  }
  .item {
    width: 100%;
    display: flex;
    margin-bottom: 15px;
    margin-top: 15px;
    > div {
      border-radius: 4px;
      flex: 1;
      margin-left: 15px;
      background: url(../../assets/item_frame.png) no-repeat;
      background-size: 100% 100%;
      display: flex;
      align-items: center;
      padding: 12px;
      img {
        width: 2.3vw;
        // height:1.7vw;
      }
      > div {
        display: flex;
        flex-direction: column;
        // margin-left: 0.8vw;
        justify-content: center;
        align-items: center;
        width: 80%;
        span:nth-of-type(1) {
          font-size: 0.75vw;
        }
        span:nth-of-type(2) {
          font-weight: bold;
          font-size: 1.2vw;
          margin-top: 0.8vw;
          span {
            font-size: 0.7vw;
          }
        }
      }
    }
  }
</style>
