<script lang="ts" name="InventoryAnalysis" setup>
import * as echarts from 'echarts';
import moment from 'moment';
import { topDataVO } from '@/api/expert/inventoryAnalysis/types';
import {
  getExpertWarehousingCount,
  getExpertPaperCount,
  getExpertPatentCount,
  getExpertNewTotalCount,
  getExpertFieldData,
  getExpertAgeRangeData,
  getExpertEducationData,
  getExpertTrendAnalysisData,
  getExpertWarehousingData
} from '@/api/expert/inventoryAnalysis';

import CommonEChart from '@/views/expert/inventoryAnalysis/echarts/commonEchart.vue';
import {
  getExpertUnitTypeData,getExpertErrorSts
} from '@/api/backStage/expertManagement/expertStatisticalReport';
import useUserStore from '@/store/modules/user';
const userStore = useUserStore();
const roles = ref(userStore.roles);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { unit_type } = toRefs<any>(proxy?.useDict('unit_type'));
const { degree_type } = toRefs<any>(proxy?.useDict('degree_type'));
const { perform_work_type } = toRefs<any>(proxy?.useDict('perform_work_type'));

const storage_error = ref([
  {
    label:'系统错误',
    value: 'sysErrorNum'
  },
  {
    label:'用户输入错误',
    value: 'webErrorNum'
  }
])

const topData = ref<topDataVO[]>([
  {
    title: '入库专家人数',
    data: 0,
    unit: '人'
  },
  {
    title: '在库论文总数',
    data: 0,
    unit: '个'
  },
  {
    title: '在库专利总数',
    data: 0,
    unit: '个'
  },
  {
    title: '本年度入库专家',
    data: 0,
    unit: '人'
  }
]);
const expertFieldActiveValue = ref<number>(30);
const tabItem = reactive([
  {
    title: '近30天',
    value: 30
  },
  {
    title: '近60天',
    value: 60
  },
  {
    title: '近90天',
    value: 90
  }
]);

const expertUnitTypeShowNoData = ref(false);
const fieldNumberShowNoData = ref(false);
const excavationFootageAnalysisShowNoData = ref(false);
const expertEducationShowNoData = ref(false);

const trendAnalysisisShowNoData = ref(false);
const warehousingisShowNoData = ref(false);
const trendAnalysisTimeValue = ref(moment(new Date()).format('YYYY-MM'));
const trendAnalysisStartTime = ref('');
const trendAnalysisEndTime = ref('');

const warehousingTimeValue = ref(moment(new Date()).format('YYYY-MM'));
const warehousingStartTime = ref('');
const warehousingEndTime = ref('');
// echartsOption 专家单位类型统计
const expertUnitTypeOption = reactive({
  color: ['#237ffd', '#1cd599', '#ea3c3f', '#6d6e6f'],
  tooltip: {
    trigger: 'item'
  },
  legend: {
    itemWidth: 5,
    itemHeight: 5,
    bottom: '0',
    left: 'center',
    textStyle: {
      color: '#ffffff'
    }
  },
  graphic: {
    elements: [
      {
        type: 'text',
        left: '49%',
        top: '30%',
        style: {
          text: 0,
          textAlign: 'center',
          fill: '#ffffff',
          width: 30,
          height: 25,
          fontSize: 18
        }
      },
      {
        type: 'text',
        left: '38%',
        top: '45%',
        style: {
          text: '专家单位类型总数',
          textAlign: 'center',
          fill: '#ffffff',
          width: 30,
          height: 30,
          fontSize: 15,
          color: '#ffffff'
        }
      }
    ]
  },
  series: [
    {
      name: '专家单位类型统计',
      type: 'pie',
      radius: ['60%', '70%'],
      top: '-15%',
      avoidLabelOverlap: false,
      padAngle: 5,
      itemStyle: {
        borderRadius: 10
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: false,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
});

// echartsOption 各个领域人数
const fieldNumberOption = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    itemWidth: 10,
    itemHeight: 10,
    right: '5%',
    textStyle: {
      color: '#ffffff'
    }
  },
  grid: {
    width: '90%',
    left: 0,
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    boundaryGap: [0, 0.01]
  },
  yAxis: {
    type: 'category',
    data: []
  },
  series: [
    {
      name: '专家人数',
      type: 'bar',
      showBackground: true,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
          { offset: 0, color: '#244467' },
          { offset: 0.5, color: '#215695' },
          { offset: 1, color: '#1b79e5' }
        ])
      },
      data: []
    }
  ]
});

// echartsOption 入库专家年龄区间
const excavationFootageAnalysisOption = reactive({
  color: ['#D96B51', '#4291DC', '#72F375'],
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#ddd'
      }
    }
  },
  grid: {
    width: '80%',
    height: '70%',
    left: '10%',
    top: '20%'
  },
  legend: {
    data: ['专家人数'],
    right: '5%',
    itemWidth: 10,
    itemHeight: 10,
    itemGap: 20,
    textStyle: {
      color: '#ffffff'
    }
  },
  xAxis: [
    {
      type: 'category',
      data: [],
      axisTick: {
        show: true
      },
      axisLabel: {
        interval: 0,
        fontSize: 10
      },
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      splitLine: {
        show: false
      }
    }
  ],
  series: [
    {
      name: '专家人数',
      type: 'bar',
      data: [1, 2, 3, 4],
      showBackground: true,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#1b79e5' },
          { offset: 0.5, color: '#215695' },
          { offset: 1, color: '#244467' }
        ])
      },
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      }
    }
  ]
});

// echartsOption 专家学历统计
const expertEducationOption = reactive({
  color: ['#D96B51', '#4291DC', '#72F375'],
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#ddd'
      }
    }
  },
  grid: {
    width: '80%',
    height: '70%',
    left: '7%',
    top: '20%'
  },
  legend: {
    data: ['专家人数'],
    right: '3%',
    top: '0',
    itemWidth: 10,
    itemHeight: 10,
    itemGap: 20,
    textStyle: {
      color: '#ffffff'
    }
  },
  xAxis: [
    {
      type: 'category',
      data: [],
      axisTick: {
        show: true
      },
      axisLabel: {
        interval: 0,
        fontSize: 10
      },
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      splitLine: {
        show: false
      }
    }
  ],
  series: [
    {
      name: '专家人数',
      type: 'bar',
      data: [],
      showBackground: true,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#1b79e5' },
          { offset: 0.5, color: '#215695' },
          { offset: 1, color: '#244467' }
        ])
      },
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      }
    }
  ]
});
// echartsOption 专家趋势分析
const expertTrendAnalysisOption = reactive({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['审批通过', '审批驳回'],
    right: '3%',
    top: '0',
    itemWidth: 10,
    itemHeight: 10,
    itemGap: 20,
    textStyle: {
      color: '#ffffff'
    }
  },
  grid: {
    width: '80%',
    left: '10%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    axisLabel: {
      interval: 2,
      rotate: 0,
      fontSize: 9
    },
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '审批通过',
      type: 'line',
      stack: 'Total',
      data: []
    },
    {
      name: '审批驳回',
      type: 'line',
      stack: 'Total',
      data: []
    }
  ]
});
// echartsOption 专家入库时间分析
const expertWarehousingOption = reactive({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#ddd'
      }
    }
  },
  grid: {
    width: '80%',
    height: '70%',
    left: '10%',
    top: '20%'
  },
  legend: {
    data: ['专家人数'],
    right: '3%',
    top: '0',
    itemWidth: 10,
    itemHeight: 10,
    itemGap: 20,
    textStyle: {
      color: '#ffffff'
    }
  },
  xAxis: [
    {
      type: 'category',
      data: [],

      axisTick: {
        show: true
      },
      axisLabel: {
        interval: 2,
        rotate: 0,
        fontSize: 9
      },
      axisPointer: {
        type: 'shadow'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      splitLine: {
        show: false
      }
    }
  ],
  series: [
    {
      name: '专家人数',
      type: 'bar',
      data: [],
      showBackground: true,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#1b79e5' },
          { offset: 0.5, color: '#215695' },
          { offset: 1, color: '#244467' }
        ])
      },
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      }
    }
  ]
});
// echartsOption 入库错误分析
const storageErrorOption = reactive({
  color: ['#ea3c3f', '#1cd599'],
  tooltip: {
    trigger: 'item'
  },
  legend: {
    itemWidth: 5,
    itemHeight: 5,
    bottom: '0',
    left: 'center',
    textStyle: {
      color: '#ffffff'
    }
  },
  graphic: {
    elements: [
      {
        type: 'text',
        left: '49%',
        top: '30%',
        style: {
          text: 0,
          textAlign: 'center',
          fill: '#ffffff',
          width: 30,
          height: 25,
          fontSize: 18
        }
      },
      {
        type: 'text',
        left: '38%',
        top: '45%',
        style: {
          text: '专家入库错误总数',
          textAlign: 'center',
          fill: '#ffffff',
          width: 30,
          height: 30,
          fontSize: 15,
          color: '#ffffff'
        }
      }
    ]
  },
  series: [
    {
      name: '入库错误分析',
      type: 'pie',
      radius: ['60%', '70%'],
      top: '-15%',
      avoidLabelOverlap: false,
      padAngle: 5,
      itemStyle: {
        borderRadius: 10
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: false,
          fontSize: 20,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
});

const tabClick = (dataValue: number) => {
  expertFieldActiveValue.value = dataValue;
  getExpertField();
};

const getExpertUnitType = async () => {
  await getExpertUnitTypeData().then(res => {
    if (res.data.length > 0) {
      let seriesData = [];
      expertUnitTypeOption.graphic.elements[0].style.text = res.data[0].totalCount || 0;
      res.data.map(item => {
        const findData = unit_type.value.find(fitem => fitem.value === item.unitType.toString());
        seriesData.push({
          value: item.count ? item.count : 0,
          name: findData ? findData.label : '未知'
        });
      });
      expertUnitTypeOption.series[0].data = seriesData;
      expertUnitTypeShowNoData.value = false;
    } else {
      expertUnitTypeShowNoData.value = true;
    }

  });
};
const getStorageError = async () => {
  if(!roles.value.includes('admin')) return;
  let res = await getExpertErrorSts()
  if (res.code === 200) {
    let seriesData = [];
    storageErrorOption.graphic.elements[0].style.text = res.data.countNum || 0;
    seriesData = storage_error.value.map(item => {
      let {label, value} = item
      return {
        value: res.data[value] || 0,
        name: label || '未知'
      }
    })
    console.log(seriesData);
    storageErrorOption.series[0].data = seriesData;
  }

  // })
};
const getExpertField = async () => {
  const params = {
    days: expertFieldActiveValue.value
  };
  await getExpertFieldData(params).then(res => {

    if (res.data.length > 0) {
      let yAxisData = [];
      let seriesData = [];
      res.data.map(item => {
        const findData = perform_work_type.value.find(fitem => fitem.value === item.performWork.toString());
        if (findData) {
          yAxisData.push(findData.label);
          seriesData.push(item.count);
        }
      });
      fieldNumberOption.yAxis.data = yAxisData;
      fieldNumberOption.series[0].data = seriesData;
      fieldNumberShowNoData.value = false;
    } else {
      fieldNumberShowNoData.value = true;
    }

  });
};
const getExpertAgeRange = async () => {
  await getExpertAgeRangeData().then(res => {
    if (res.data.length > 0) {
      let xAxisData = [];
      let seriesData = [];
      res.data.map(item => {
        xAxisData.push(item.age_range);
        seriesData.push(item.count);
      });
      excavationFootageAnalysisOption.xAxis[0].data = xAxisData;
      excavationFootageAnalysisOption.series[0].data = seriesData;
      excavationFootageAnalysisShowNoData.value = false;
    } else {
      excavationFootageAnalysisShowNoData.value = true;
    }

  });
};
const getExpertEducation = async () => {
  await getExpertEducationData().then(res => {
    if (res.data.length > 0) {
      let xAxisData = [];
      let seriesData = [];
      res.data.map(item => {
        const findData = degree_type.value.find(fitem => fitem.value === item.degree.toString());
        xAxisData.push(findData.label);
        seriesData.push(item.count);
      });
      expertEducationOption.xAxis[0].data = xAxisData;
      expertEducationOption.series[0].data = seriesData;
      expertEducationShowNoData.value = false;
    } else {
      expertEducationShowNoData.value = true;
    }

  });
};
const getExpertTrendAnalysis = async () => {
  const params = {
    startTime: trendAnalysisStartTime.value,
    endTime: trendAnalysisEndTime.value
  };
  await getExpertTrendAnalysisData(params).then(res => {
    let xAxisData = [];
    let successSeriesData = [];
    let errorSeriesData = [];
    if (res.data.length > 0) {
      res.data.map(item => {
        xAxisData.push(item.application_date);
        successSeriesData.push(item.successCount);
        errorSeriesData.push(item.errorCount);
      });
      expertTrendAnalysisOption.xAxis.data = xAxisData;
      expertTrendAnalysisOption.series[0].data = successSeriesData;
      expertTrendAnalysisOption.series[1].data = errorSeriesData;
      trendAnalysisisShowNoData.value = false;
    } else {
      trendAnalysisisShowNoData.value = true;
    }

  });
};

const getExpertWarehousing = async () => {
  const params = {
    startTime: warehousingStartTime.value,
    endTime: warehousingEndTime.value
  };
  await getExpertWarehousingData(params).then(res => {
    let xAxisData = [];
    let seriesData = [];
    if (res.data.length > 0) {
      res.data.map(item => {
        xAxisData.push(item.approval_date);
        seriesData.push(item.approval_count);
      });
      warehousingisShowNoData.value = false;
      expertWarehousingOption.xAxis[0].data = xAxisData;
      expertWarehousingOption.series[0].data = seriesData;
    } else {
      warehousingisShowNoData.value = true;
    }

  });
};

const getTopData = async () => {
  await getExpertWarehousingCount().then(res => {
    topData.value[0].data = res.data.toString();
  });
  await getExpertPaperCount().then(res => {
    topData.value[1].data = res.data.toString();
  });
  await getExpertPatentCount().then(res => {
    topData.value[2].data = res.data.toString();
  });
  await getExpertNewTotalCount().then(res => {
    topData.value[3].data = res.data.toString();
  });
};

const trendAnalysisTimeChange = () => {
  const totalDays = moment(trendAnalysisTimeValue.value, 'YYYY-MM').daysInMonth();
  trendAnalysisStartTime.value = trendAnalysisTimeValue.value + '-01';
  trendAnalysisEndTime.value = trendAnalysisTimeValue.value + '-' + totalDays;
  getExpertTrendAnalysis();
};
const warehousingTimeChange = () => {
  const totalDays = moment(warehousingTimeValue.value, 'YYYY-MM').daysInMonth();
  warehousingStartTime.value = warehousingTimeValue.value + '-01';
  warehousingEndTime.value = warehousingTimeValue.value + '-' + totalDays;
  getExpertWarehousing();
};
getExpertUnitType();
getExpertField();
getExpertAgeRange();
getExpertEducation();
getExpertTrendAnalysis();
getExpertWarehousing();
getStorageError();
onActivated(() => {
  getExpertUnitType();
  getExpertField();
  getExpertAgeRange();
  getExpertEducation();
  getExpertTrendAnalysis();
  getExpertWarehousing();
  getStorageError();
});
onMounted(() => {
  getTopData();
});
</script>

<template>
  <div class="app-container home">
    <div class="inventoryAnalysisBox">
      <el-card style="width: 100%; margin-bottom: 20px">
        <div class="topStatisticsBox">
          <div v-for="(item, index) in topData" :class="'bgColor' + index" class="statisticsItemBox">
            <div class="titleName">
              {{ item.title }}
            </div>
            <div class="dataBox">
              <div class="leftData">
                {{ item.data }}
              </div>
              <div class="rightUnit">
                {{ item.unit }}
              </div>
            </div>
          </div>
        </div>
      </el-card>
      <el-card style="width: 100%">
        <div class="analysisContentBox">
          <div class="contentBox">
            <div class="commonStatisticsBox">
              <div class="statisticsHeadBox">
                <div class="leftTitle">专家单位类型统计</div>
              </div>
              <div class="echartContentBox">
                <CommonEChart :echartHeight="250" :isShowNo="expertUnitTypeShowNoData" :options="expertUnitTypeOption" />
              </div>
            </div>
            <div class="commonStatisticsBox">
              <div class="statisticsHeadBox">
                <div class="leftTitle">各个领域人数</div>
                <div class="topTabBox">
                  <div
                    v-for="item in tabItem"
                    :class="{ tabActive: item.value === expertFieldActiveValue }"
                    class="tabItem"
                    @click="tabClick(item.value)"
                  >
                    {{ item.title }}
                  </div>
                </div>
              </div>
              <div class="echartContentBox">
                <CommonEChart
                  :echartHeight="250"
                  :isShowNo="fieldNumberShowNoData"
                  :options="fieldNumberOption"
                  :timerDate="expertFieldActiveValue"
                />
              </div>
            </div>
            <div class="commonStatisticsBox">
              <div class="statisticsHeadBox">
                <div class="leftTitle">入库专家年龄区间</div>
              </div>
              <div class="echartContentBox">
                <CommonEChart :echartHeight="250" :isShowNo="excavationFootageAnalysisShowNoData" :options="excavationFootageAnalysisOption" />
              </div>
            </div>
            <div class="commonStatisticsBox">
              <div class="statisticsHeadBox">
                <div class="leftTitle">入库专家各个学历的人数</div>
                <div class="rightTimeBox"></div>
              </div>
              <div class="echartContentBox">
                <CommonEChart :echartHeight="250" :isShowNo="expertEducationShowNoData" :options="expertEducationOption" />
              </div>
            </div>
            <div class="commonStatisticsBox">
              <div class="statisticsHeadBox">
                <div class="leftTitle">专家入库时间分析</div>
                <div class="rightTimeBox">
                  <el-date-picker
                    v-model="warehousingTimeValue"
                    :clearable="false"
                    format="YYYY-MM"
                    placeholder="请选择"
                    type="month"
                    value-format="YYYY-MM"
                    @change="warehousingTimeChange"
                  />
                </div>
              </div>
              <div class="echartContentBox">
                <CommonEChart :echartHeight="250" :isShowNo="warehousingisShowNoData" :options="expertWarehousingOption" />
              </div>
            </div>
            <div class="commonStatisticsBox">
              <div class="statisticsHeadBox">
                <div class="leftTitle">趋势分析</div>
                <div class="rightTimeBox">
                  <el-date-picker
                    v-model="trendAnalysisTimeValue"
                    :clearable="false"
                    format="YYYY-MM"
                    placeholder="请选择"
                    type="month"
                    value-format="YYYY-MM"
                    @change="trendAnalysisTimeChange"
                  />
                </div>
              </div>
              <div class="echartContentBox">
                <CommonEChart :echartHeight="250" :isShowNo="trendAnalysisisShowNoData" :options="expertTrendAnalysisOption" />
              </div>
            </div>

            <div class="commonStatisticsBox" v-if="roles.includes('admin')">
              <div class="statisticsHeadBox">
                <div class="leftTitle">入库错误分析</div>
              </div>
              <div class="echartContentBox">
                <CommonEChart :echartHeight="250" :isShowNo="false" :options="storageErrorOption" />
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.inventoryAnalysisBox {
  .topStatisticsBox {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .statisticsItemBox {
      width: 24%;
      height: 150px;
      border: 1px solid #dddddd;
      border-radius: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-wrap: wrap;
      color: #ffffff;
      box-shadow: 5px 5px 12px rgba(0, 0, 0, 0.2);

      &.bgColor0 {
        background-color: #3f9dc6;
      }

      &.bgColor1 {
        background-color: #d9021d;
      }

      &.bgColor2 {
        background-color: #f59b25;
      }

      &.bgColor3 {
        background-color: #1ab394;
      }

      .titleName {
        width: 100%;
        text-align: center;
      }

      .dataBox {
        width: 100%;
        text-align: center;
        display: flex;
        justify-content: center;
        align-items: flex-end;

        .rightUnit {
          font-size: 13px;
          padding-left: 5px;
        }
      }
    }
  }

  .analysisContentBox {
    .contentBox {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;

      .commonStatisticsBox {
        width: 33%;
        border-radius: 10px;
        background-color: #0e233b;
        margin-bottom: 20px;

        .statisticsHeadBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 20px;
          min-height: 75px;

          .leftTitle {
            font-family: PingFang SC;
            font-size: 16px;
            font-weight: 600;
            line-height: 10px;
            letter-spacing: 0.1em;
            text-align: left;
            color: #ffffff;
            font-style: italic;
            position: relative;
            padding-left: 15px;
            margin-top: 5px;

            &::after {
              content: '';
              position: absolute;
              width: 3px;
              height: 15px;
              border-radius: 2px;
              top: 0;
              left: 0;
              background-color: #1c84c6;
            }
          }

          .topTabBox {
            width: 50%;
            display: flex;
            justify-content: flex-end;
            align-items: center;

            .tabItem {
              width: 50px;
              height: 20px;
              border: 1px solid #dddddd;
              text-align: center;
              line-height: 20px;
              cursor: pointer;
              font-size: 10px;
              color: #dddddd;

              &.tabActive {
                background-color: #1c84c6;
                color: #ffffff;
              }

              &:nth-child(2n) {
                border-left: unset;
                border-right: unset;
              }
            }
          }
        }

        .echartContentBox {
          height: 35vh;
        }
      }
    }
  }
}
</style>
