<template>
  <div class="dispatch-analysis">
    <report-header
      title="派单分析"
      v-model:dateRange="curTimeRange"
      @timeChange="timeChange"
    ></report-header>
    <div class="page-main">
      <div class="scroll-content">
        <div class="row1 flex">
          <div class="col1">
            <div class="card chart1-box" v-loading="loading1">
              <div class="title">客户类型</div>
              <div class="chart-wrap"
                ><my-chart
                  :options="options1"
                  @chartClick="chart1Click"
                ></my-chart
              ></div>
            </div>
            <div class="card chart2-box">
              <div class="title"
                ><span>研究生月度派单分配及对比</span>
                <FullscreenIcon
                  class="cursor-pointer"
                  @click="chart2?.maximize"
                  color="#595959"
              /></div>
              <div class="chart-wrap"
                ><my-chart
                  :options="options2"
                  @chartClick="chart2Click"
                  ref="chart2"
                ></my-chart
              ></div>
            </div>
          </div>
          <div class="col2 flex-1">
            <div class="statistics flex items-center">
              <div class="num-box flex h-full items-center">
                <span class="title">派单累计</span>
                <div class="num num1">
                  <span
                    :class="{
                      num: item.type === 'num',
                      split: item.type === 'split',
                    }"
                    v-for="(item, index) in crmArr"
                    :key="index"
                    >{{ item.num }}</span
                  >
                </div>
              </div>
              <div class="num-box flex h-full items-center">
                <span class="title">服务人次累计</span>
                <div class="num num2">
                  <span
                    :class="{
                      num: item.type === 'num',
                      split: item.type === 'split',
                    }"
                    v-for="(item, index) in personArr"
                    :key="index"
                    >{{ item.num }}</span
                  ></div
                >
              </div>
            </div>
            <div class="china-box card">
              <ChinaPointChart
                :data="chinaDataHandle(result5, result8)"
              ></ChinaPointChart>
            </div>
          </div>
          <div class="col3">
            <div class="card chart4-box">
              <div class="title">供应商派单分布</div>
              <div class="chart-wrap"
                ><my-chart
                  :options="options4"
                  @chartClick="chart4Click"
                ></my-chart
              ></div>
            </div>
            <div class="card chart5-box">
              <div class="title">研究生城市在执行派单排名</div>
              <div class="chart-wrap">
                <table-loop
                  :data="tableDataHandle(result5)"
                  :columns="tableColumns"
                  @rowClick="tableRowClick5"
                ></table-loop>
              </div>
            </div>
          </div>
        </div>
        <div class="row2 flex">
          <div class="col1">
            <div class="card chart6-box">
              <div class="title"
                ><span>教务处月度派单分布及对比备份</span
                ><FullscreenIcon
                  class="cursor-pointer"
                  @click="chart3?.maximize"
                  color="#595959"
              /></div>
              <div class="chart-wrap">
                <my-chart
                  :options="options3"
                  @chartClick="chart3Click"
                  ref="chart3"
                ></my-chart>
              </div>
            </div>
          </div>
          <div class="col2">
            <div class="card chart7-box">
              <div class="title m-b-8px">项目派单完成率</div>
              <div class="chart-wrap overflow-auto service-box">
                <div
                  class="service-item"
                  v-for="item in result6"
                  :key="item.id"
                  @click="serviceClick(item)"
                >
                  <div class="head flex justify-between items-center">
                    <div>{{ item.name }}</div>
                    <div>{{ item.rate }}</div>
                  </div>
                  <div class="body flex items-center">
                    <div class="label">状态：</div>
                    <div
                      class="status"
                      :class="{ finished: item.rate === '100%' }"
                      >{{ item.rate === '100%' ? '已完成' : '已发布' }}</div
                    >
                    <div class="process-box">
                      <div class="process" :style="{ width: item.rate }"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col3">
            <div class="card chart8-box">
              <div class="title">教务处城市在执行派单排名</div>
              <div class="chart-wrap">
                <table-loop
                  :data="tableDataHandle(result8)"
                  :columns="tableColumns"
                  @rowClick="tableRowClick6"
                ></table-loop>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <CustomTypeDrillDialog
      v-model:visible="showCustomTypeDrill"
      :data="customTypeDrillData"
      :footer="false"
      :timeParams="timeParams"
    ></CustomTypeDrillDialog>
    <MonthDispatchDrillDialog
      v-model:visible="showMonthDispatchDrill"
      :data="monthDispatchDrillData"
      :footer="false"
      :timeParams="timeParams"
    ></MonthDispatchDrillDialog>
    <RegionDispatchDrillDialog
      v-model:visible="showRegionDispatchDrill"
      :data="regionDispatchDrillData"
      :footer="false"
      :timeParams="timeParams"
    ></RegionDispatchDrillDialog>
    <SupplierDispatchDrillDialog
      v-model:visible="showSupplierDispatchDrill"
      :data="supplierDispatchDrillData"
      :footer="false"
      :timeParams="timeParams"
    ></SupplierDispatchDrillDialog>
    <DispatchStatisticsDrill
      v-model:visible="showDispatchStatisticsDrill"
      :data="dispatchStatisticsDrillData"
      :footer="false"
      :timeParams="timeParams"
    ></DispatchStatisticsDrill>
  </div>
</template>

<script setup name="DispatchAnalysis">
import { ref, computed, onMounted } from 'vue';
import ChinaPointChart from '@/components/common/china-point-chart/index.vue';
import TableLoop from '@/components/common/table-loop/index.vue';
import { CUSTOMER_TYPE } from '@/config/constants';
import { useRequest } from 'vue-request';
import CustomTypeDrillDialog from './custom-type-drill-dialog.vue';
import MonthDispatchDrillDialog from './month-dispatch-drill-dialog.vue';
import RegionDispatchDrillDialog from './region-dispatch-drill-dialog.vue';
import SupplierDispatchDrillDialog from './supplier-dispatch-drill-dialog.vue';
import DispatchStatisticsDrill from './dispatch-statistics-drill-dialog.vue';
import { FullscreenIcon } from 'tdesign-icons-vue-next';

import {
  createBarOption,
  createRingPieOption,
  createCakePieOption,
} from '@/utils/chart';
import {
  customTypeAnalysis,
  monthDispatchAnalysis,
  dispatchRankingAnalysis,
  supplierDispatchAnalysis,
  dispatchStatisticsAnalysis,
  dispatchProjectCount,
} from '@/api/report';
import { groupSeparator } from '@/utils/tool';
const chart2 = ref();
const chart3 = ref();
const showCustomTypeDrill = ref(false);
const customTypeDrillData = ref({ type: '' });

const showMonthDispatchDrill = ref(false);
const monthDispatchDrillData = ref({ type: '', month: '' });

const showRegionDispatchDrill = ref(false);
const regionDispatchDrillData = ref({ type: '', regionId: '', name: '' });

const showSupplierDispatchDrill = ref(false);
const supplierDispatchDrillData = ref({ supplierId: '', name: '' });

const showDispatchStatisticsDrill = ref(false);
const dispatchStatisticsDrillData = ref({ serviceId: '', serviceName: '' });

const curTimeRange = ref([]);
const timeParams = computed(() => {
  return {
    startTime: new Date(curTimeRange.value[0] + ' 00:00:00').getTime(),
    endTime: new Date(curTimeRange.value[1] + ' 23:59:59').getTime(),
  };
});
const {
  data: result1,
  loading: loading1,
  run: run1,
} = useRequest(customTypeAnalysis);
const {
  data: result2,
  loading: loading2,
  run: run2,
} = useRequest(monthDispatchAnalysis);
const comResult2 = computed(() => {
  return barDataHandle(result2.value);
});
const comResult3 = computed(() => {
  return barDataHandle(result3.value);
});
const {
  data: result3,
  loading: loading3,
  run: run3,
} = useRequest(monthDispatchAnalysis);
const {
  data: result4,
  loading: loading4,
  run: run4,
} = useRequest(supplierDispatchAnalysis);
const {
  data: result5,
  loading: loading5,
  run: run5,
} = useRequest(dispatchRankingAnalysis);
const {
  data: result6,
  loading: loading6,
  run: run6,
} = useRequest(dispatchStatisticsAnalysis);
const {
  data: result8,
  loading: loading8,
  run: run8,
} = useRequest(dispatchRankingAnalysis);

const {
  data: result9,
  loading: loading9,
  run: run9,
} = useRequest(dispatchProjectCount);
const crmArr = computed(() => {
  let num = result9.value?.crm || '';
  let numStr = groupSeparator(num);
  return numStr.split('').map((item) => {
    return {
      num: item,
      type: !isNaN(Number(item)) ? 'num' : 'split',
    };
  });
});

const personArr = computed(() => {
  let num = result9.value?.person || '';
  let numStr = groupSeparator(num);
  return numStr.split('').map((item) => {
    return {
      num: item,
      type: Number(item) ? 'num' : 'split',
    };
  });
});
const chinaDataHandle = (result5, result8) => {
  if (!result5 || !result8) {
    return null;
  } else {
    let arr5 = (result5 || []).map((item) => {
      item.value = Number(item.count);
      return item;
    });
    let arr8 = (result8 || []).map((item) => {
      item.value = Number(item.count);
      return item;
    });
    return [
      { name: '教务处', data: arr8 },
      { name: '研究生', data: arr5 },
    ];
  }
};

const barDataHandle = (result) => {
  if (!result) {
    return { xData: [], seriesData: [] };
  } else {
    const { lastYear, year } = result;
    let lastYear2 = year.map((item) => {
      let find = lastYear.find((v) => v.month == item.month);
      return find ? find : { ...item, count: 0 };
    });
    return {
      xData: year.map((item) => `${item.year}-${item.month}`),
      seriesData: [
        { name: '当期', data: year.map((item) => item.count) },
        { name: '同期', data: lastYear2.map((item) => item.count) },
      ],
    };
  }
};

const tableColumns = [
  {
    prop: 'name',
    label: '城市',
    style: { width: '80px' },
  },
  {
    prop: 'count',
    label: '总数',
    style: { width: '37px' },
  },
  {
    prop: 'rate',
    label: '百分比',
    style: { width: '50px' },
  },
  { prop: 'compare', label: '增减', style: { width: '40px' } },
];
const tableDataHandle = (data) => {
  if (!data) {
    return [];
  } else {
    // let totalCount = data.day.reduce((num, item) => {
    //   return num + item.count;
    // }, 0);
    // return data.day.map((item) => {
    //   item.rate = ((item.count * 100) / totalCount).toFixed(2) + '%';
    //   return item;
    // });
    return data;
    // let totalCount = data.day.reduce((num, item) => {
    //   return num + item.count;
    // }, 0);
    // return data.day.map((item) => {
    //   item.rate = ((item.count * 100) / totalCount).toFixed(2) + '%';
    //   return item;
    // });
    return data;
  }
};
onMounted(() => {
  run1({ ...timeParams.value });
  run2({ ...timeParams.value, type: 'CLOUD_MARK' });
  run3({ ...timeParams.value, type: 'OFFICE' });
  run4({ ...timeParams.value });
  run5({ ...timeParams.value, type: 'CLOUD_MARK' });
  run6({ ...timeParams.value });
  run8({ ...timeParams.value, type: 'OFFICE' });
  run9({ ...timeParams.value });
});
const timeChange = () => {
  run1({ ...timeParams.value });
  run2({ ...timeParams.value, type: 'CLOUD_MARK' });
  run3({ ...timeParams.value, type: 'OFFICE' });
  run4({ ...timeParams.value });
  run5({ ...timeParams.value, type: 'CLOUD_MARK' });
  run6({ ...timeParams.value });
  run8({ ...timeParams.value, type: 'OFFICE' });
  run9({ ...timeParams.value });
};
const options1 = computed(() => {
  return createRingPieOption(
    {
      data: Object.entries(result1.value || {}).map((item) => ({
        name: CUSTOMER_TYPE[item[0]],
        value: item[1],
      })),
      title: '总数',
      center: ['50%', '40%'],
      seriesName: '客户类型',
      radius: [30, 50],
    },
    {
      legend: {
        top: null,
        right: null,
        left: 'center',
        bottom: 0,
        orient: 'horizontal',
        type: 'scroll',
      },
    }
  );
});
const chart1Click = (params) => {
  customTypeDrillData.value.type =
    params.data.name === '研究生' ? 'CLOUD_MARK' : 'OFFICE';
  showCustomTypeDrill.value = true;
};
const chart2Click = (params) => {
  monthDispatchDrillData.value.type = 'CLOUD_MARK';
  monthDispatchDrillData.value.year = params.name.split('-')[0];
  monthDispatchDrillData.value.month = params.name.split('-')[1];
  showMonthDispatchDrill.value = true;
};
const chart3Click = (params) => {
  monthDispatchDrillData.value.type = 'OFFICE';
  monthDispatchDrillData.value.year = params.name.split('-')[0];
  monthDispatchDrillData.value.month = params.name.split('-')[1];
  showMonthDispatchDrill.value = true;
};
const chart4Click = (params) => {
  supplierDispatchDrillData.value.name = params.name;
  supplierDispatchDrillData.value.supplierId = params.data.id;
  showSupplierDispatchDrill.value = true;
};

const tableRowClick5 = (item) => {
  regionDispatchDrillData.value.type = 'CLOUD_MARK';
  // regionDispatchDrillData.value.regionId = item.id;
  regionDispatchDrillData.value.name = item.name;
  showRegionDispatchDrill.value = true;
};

const tableRowClick6 = (item) => {
  regionDispatchDrillData.value.type = 'OFFICE';
  // regionDispatchDrillData.value.regionId = item.id;
  regionDispatchDrillData.value.name = item.name;
  showRegionDispatchDrill.value = true;
};

const serviceClick = (item) => {
  dispatchStatisticsDrillData.value.serviceId = item.id;
  dispatchStatisticsDrillData.value.serviceName = item.name;
  showDispatchStatisticsDrill.value = true;
};

const options2 = computed(() => {
  return createBarOption(comResult2.value);
});
const options3 = computed(() => {
  return createBarOption(comResult3.value);
});

const options4 = computed(() =>
  createCakePieOption(
    {
      data: (result4.value || []).map((item) => {
        item.value = item.count;
        return item;
      }),
      center: ['50%', '38%'],
      radius: [0, 50],
    },
    {
      legend: {
        top: null,
        right: null,
        left: 'center',
        bottom: 0,
        orient: 'horizontal',
        type: 'scroll',
      },
    }
  )
);
</script>

<style lang="less" scoped>
.dispatch-analysis {
  .page-main {
    height: calc(100vh - 57px);
    padding: 15px;
    overflow: auto;
    .scroll-content {
      height: 100%;
      min-height: 600px;
      min-width: 1000px;
    }
    .row1 {
      height: calc((100% - 30px) * 2 / 3 + 15px);
    }
    .row2 {
      height: calc((100% - 30px) / 3);
      margin-top: 15px;
    }
    .col1,
    .col3 {
      width: 268px;
      height: calc((100% - 30px) * 2 / 3 + 15px);
    }
    .col2 {
      width: calc(100% - 566px);
      margin-left: 15px;
      margin-right: 15px;
      .statistics {
        border: 1px solid #e5e5e5;
        background: #ffffff;
        border-radius: 4px;
        height: 64px;
        .num-box {
          width: 50%;
          .title {
            font-size: 14px;
            color: #595959;
            padding-left: 10px;
            margin-right: 6px;
          }
          .num {
            margin-right: 5px;
            font-size: 14px;
            font-weight: bold;
            display: flex;
            align-items: center;
            justify-content: center;
            & > span {
              &.num {
                width: 22px;
                height: 32px;
                background: #f7f7f7;
                border-radius: 2px;
                border: 1px solid #e5e5e5;
              }
              &.split {
                color: #262626;
              }
            }
            &.num1 {
              color: #ff7d00;
            }
            &.num2 {
              color: #00b42a;
            }
          }
        }
      }
      .china-box {
        height: calc(100% - 79px);
        margin-top: 15px;
      }
    }
    .row2 {
      .col1,
      .col3 {
        height: 100%;
        .card {
          height: 100%;
        }
      }
    }
    .row1 {
      .col1,
      .col3 {
        height: 100%;
        .card {
          height: calc((100% - 15px) / 2);
          &:not(:first-child) {
            margin-top: 15px;
          }
        }
      }
    }
    .row2 {
      .card {
        height: 100%;
      }
    }
    .card {
      padding: 4px 10px 10px 10px;
      background-color: #fff;
      border: 1px solid #e5e5e5;
      border-radius: 4px;
      .title {
        height: 36px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .label {
          color: #262626;
          font-size: 14px;
          // font-weight: bold;
        }
      }
      .chart-wrap {
        height: calc(100% - 36px);
        padding: 2px;
        &.service-box {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          align-content: flex-start;
        }
        .service-item {
          height: 54px;
          width: calc(50% - 8px);
          margin-bottom: 8px;
          padding: 6px 8px;
          background-color: #f7f7f7;
          border-radius: 2px;
          cursor: pointer;
          &:hover {
            box-shadow: 0 0 0 2px #4080ff;
          }

          .head {
            font-size: 12px;
            color: #262626;
          }
          .body {
            font-size: 12px;
            .label {
              color: #8c8c8c;
            }
            .status {
              color: #ff7d00;
              &.finished {
                color: #00b42a;
              }
            }
            .process-box {
              flex: 1;
              margin-left: 30px;
              background-color: #d9d9d9;
              height: 6px;
              border-radius: 3px;
              width: 90%;
              overflow: hidden;
              .process {
                background-color: #4080ff;
                height: 100%;
              }
            }
          }
        }
      }
    }
  }
}
</style>
