import { defineComponent, onMounted, ref, computed, PropType, watch, onUnmounted } from "vue";
import { Select, DatePicker, Radio, Drawer, Input, Table, Button, Tabs } from "ant-design-vue";
import { DownOutlined, SearchOutlined } from "@ant-design/icons-vue";
import locale from "ant-design-vue/es/date-picker/locale/zh_CN";
import * as echarts from "echarts";
import html2canvas from "html2canvas";

import { getRadarOption } from "./reportInfo/chartOptions";
import { StatisticsData } from "./reportInfo/options";
import {
  StatisticsDataForVehicle,
  Statistics,
  EnumEnterprise,
  StatisticsDataForEnterprise,
} from "@/store/enterpriseReport/types";
import { getFormatedStatisticeDataForEnterprise, getFormatedStatisticsDataForVehicle } from "./reportInfo/fetchData";
import useEnterpriseStore from "@/store/enterpriseReport";
import { useStore } from "@/hook/useStore";

import style from "@/assets/style/Report/reportInfo.module.less";
import DownloadIcon from "@/assets/img/roadUnit/download.svg";
import BackIcon from "@/assets/img/roadUnit/back.svg";
import useGlobalState from "@/store/global";

const { Option } = Select;
const { Group: RadioGroup, Button: RadioButton } = Radio;

/**
 * header组件
 * 包含企业选择和时间选择
 */
const Header = defineComponent({
  setup() {
    /**
     * enterpriseData: 企业体检指标统计表
     * vehicleData: 单车体检指标统计表
     */
    const { enterpriseData, allEnterprisesData, vehicleData, mapShowData, filters } = useStore(useEnterpriseStore);
    /**
         * 深圳市区域列表
         */
    const { areaList } = useStore(useGlobalState);
    /**
     * 公司名称
     */
    // const filterEnterpriseName = ref<string>("深圳市鸿利华土石方运输有限公司");

    /**
     * 选择日期
     */
    // const date = ref<string>("2021-04-20");
    // filterDate.value = date.value;
    /**
     * 企业切换
     */
    const enterpriseChange = (e: string) => {
      filters.value.enterpriseName = e;
      filters.value.plate = '';
      // enterpriseData.value&&(enterpriseData.value.enterprise_name = e);
    };
    const plateChange = (e: string) => {
      filters.value.plate = e;
      // enterpriseData.value&&(enterpriseData.value.enterprise_name = e);
    };


    /**
     * 获取企业数据
     */
    const getEnterpriseData = () => {
      // 企业整体信息
      getFormatedStatisticeDataForEnterprise(filters.value).then((data) => {
        enterpriseData.value = data.enterpriseFormatedData;
        mapShowData.value = data.enterpriseFormatedData;
        allEnterprisesData.value = data.allEnterprisesFormatedData;
      });

      // 企业车辆信息
      getFormatedStatisticsDataForVehicle(filters.value.date, filters.value.enterpriseName, '').then((data) => {
        vehicleData.value = data;
      });
    };
    getEnterpriseData();
    watch([() => filters.value.areaName, () => filters.value.enterpriseName, () => filters.value.plate], () => {
      getEnterpriseData();
    });

    watch(() => filters.value.date, () => {
      getEnterpriseData();
    })

    const exportCanvas = () => {
      const app = document.getElementById("app");
      app &&
        html2canvas(app).then((canvas) => {
          const dom = document.createElement("a");
          dom.href = canvas.toDataURL("image/png");
          dom.download = new Date().getTime() + ".png";
          dom.click();
        });
    };
    const areaChange = (area: string) => {
      filters.value.areaName = area;
      filters.value.enterpriseName = '';
      filters.value.plate = '';
    };
    return () => (
      <div class={style.header}>
        <div class={style.areaName}>
          <span style="" class={style.areaNameText}>{filters.value.areaName}</span>
          <img class={style.download} src={DownloadIcon} onClick={() => exportCanvas()} />
        </div>
        <div class={style.companyName}>
          <Select
            value={filters.value.enterpriseName ? filters.value.enterpriseName : undefined}
            v-slots={{
              suffixIcon: () => <DownOutlined style={{ fontSize: "18px", color: "#fff" }} />,
            }}
            onChange={(e: string) => enterpriseChange(e)}
            placeholder={'请选择企业'}
          >
            <Option key={''} value={''}>
              所有企业
            </Option>
            {Object.keys(EnumEnterprise).map((item) => (
              <Option key={item} value={item}>
                {item}
              </Option>
            ))}
          </Select>

          {/* </div>
        <div class={style.companyName}> */}
          <Select
            value={filters.value.plate ? filters.value.plate : undefined}
            v-slots={{
              suffixIcon: () => <DownOutlined style={{ fontSize: "18px", color: "#fff" }} />,
            }}
            onChange={(e: string) => plateChange(e)}
            placeholder={'所有车辆'}
          >
            <Option key={''} value={''}>
              所有车辆
            </Option>
            {vehicleData.value.map((item) => (
              <Option key={item.plate} value={item.plate}>
                {item.plate}
              </Option>
            ))}
          </Select>

        </div>

        {/* <div class={style.timeRange}>
          <DatePicker
            size="large"
            value={filterDate.value}
            valueFormat="YYYY-MM-DD"
            locale={locale}
            onChange={(date, dateString) => dateOnChange(dateString)}
          />
        </div> */}
      </div>
    );
  },
});

/**
 * Body
 */
const Body = defineComponent({
  setup() {
    /**
     * 切换企业概况/车辆列表
     */
    const tab = ref("enterprise");
    const tabChange = (e: string) => {
      tab.value = e;
    };

    return () => (
      <div class={style.body}>
        {/* <RadioGroup value={tab} buttonStyle="solid" onChange={(e) => tabChange(e.target.value)}>
          <RadioButton value="enterprise">概况</RadioButton>
          <RadioButton value="vehicle">车辆列表</RadioButton>
        </RadioGroup> */}
        <Content tab={tab.value} />
      </div>
    );
  },
});


const EnterpriseRankList = defineComponent({
  setup() {
    const { allEnterprisesData } = useStore(useEnterpriseStore);
    const columns = [
      {
        title: "管辖区域",
        dataIndex: "area_name",
        key: "area_name",
        width: 90,
        ellipsis: true,
      },
      {
        title: "企业",
        dataIndex: "enterprise_name",
        key: "enterprise_name",
        ellipsis: true,
        width: 130,
      },
      {
        title: "导航使用率",
        dataIndex: "guidance_usage_ratio",
        key: "guidance_usage_ratio",
        sorter: (a: any, b: any) => a.guidance_usage_ratio * 1 - b.guidance_usage_ratio * 1,
        defaultSortOrder: 'descend',
        customRender: (column: any) => (
          <span> {column.text ? (column.text + '%') : '-'}</span>
        ),
      },

    ];
    // const dataSource = ref<any[]>([]);
    return () => (
      <div class={style.rankTable}>
        <div class={style.hd}>企业排行</div>
        <Table dataSource={allEnterprisesData.value} columns={columns} size={"small"} pagination={false} bordered={false} scroll={{ y: 300 }} >
        </Table>
      </div>
    );
  },
});


const PlateRankList = defineComponent({
  setup() {
    const { vehicleData } = useStore(useEnterpriseStore);
    const columns = [
      {
        title: "企业",
        dataIndex: "enterprise_name",
        key: "enterprise_name",
        width: 130,
        ellipsis: true,
      },
      {
        title: "车牌号",
        dataIndex: "plate",
        key: "plate",
        ellipsis: true,
        width: 90,
      },
      {
        title: "导航使用率",
        dataIndex: "guidance_usage_ratio",
        key: "guidance_usage_ratio",
        sorter: (a: any, b: any) => a.guidance_usage_ratio * 1 - b.guidance_usage_ratio * 1,
        defaultSortOrder: 'descend',
        customRender: (column: any) => (
          <span> {column.text ? (column.text + '%') : '-'}</span>
        ),
      },

    ];
    // const dataSource = ref<any[]>([]);
    return () => (
      <div class={style.rankTable}>
        <div class={style.hd}>车辆排行</div>
        <Table dataSource={vehicleData.value} columns={columns} size={"small"} pagination={false} bordered={false} scroll={{ y: 300 }} >
        </Table>
      </div>
    );
  },
});
/**
 * Content
 */
const Content = defineComponent({
  props: {
    tab: {
      type: String,
      default: "enterprise",
    },
  },
  setup(props) {
    /**
     * 企业信息
     */
    const { enterpriseData, allEnterprisesData, filters } = useStore(useEnterpriseStore);

    /**
     * 企业/车辆统计数据
     */
    const statisticsList = computed(() => {
      return StatisticsData.map((item) => {
        item.count = enterpriseData.value && item.field ? enterpriseData.value[item.field] : 0;
        item.per = enterpriseData.value && item.perField ? enterpriseData.value[item.perField] : 0;
        return item;
      });
    });

    const enterprisesAverageData = computed(() => {
      const accData = allEnterprisesData.value?.reduce((acc, cur) => {
        if (!acc.area_name) {
          acc = { ...cur };
        } else {
          acc.route_regular_degree += cur.route_regular_degree;
          acc.vacant_time_ratio += cur.vacant_time_ratio;
          acc.parking_concentrate_degree += cur.parking_concentrate_degree;
          acc.driving_standard_degree += cur.driving_standard_degree;
          acc.guidance_usage_ratio += cur.guidance_usage_ratio;
        }
        return acc;
      }, {} as StatisticsDataForEnterprise);
      const length = allEnterprisesData.value?.length;
      if (accData && length) {
        return {
          ...accData,
          route_regular_degree: accData.route_regular_degree / length,
          vacant_time_ratio: accData.vacant_time_ratio / length,
          parking_concentrate_degree: accData.parking_concentrate_degree / length,
          driving_standard_degree: accData.driving_standard_degree / length,
          guidance_usage_ratio: accData.guidance_usage_ratio / length,
        };
      } else {
        return undefined;
      }
    });
    /**
     * 雷达图数据
     */
    const radarData = computed(() => {
      const option = getRadarOption();
      option.series[0].data[1].value = enterpriseData.value
        ? [
          enterpriseData.value.route_regular_degree,
          enterpriseData.value.vacant_time_ratio,
          enterpriseData.value.parking_concentrate_degree,
          enterpriseData.value.driving_standard_degree,
          enterpriseData.value.guidance_usage_ratio,
        ]
        : [0, 0, 0, 0, 0];
      option.series[0].data[0].value = enterprisesAverageData.value
        ? [
          enterprisesAverageData.value.route_regular_degree,
          enterprisesAverageData.value.vacant_time_ratio,
          enterprisesAverageData.value.parking_concentrate_degree,
          enterprisesAverageData.value.driving_standard_degree,
          enterprisesAverageData.value.guidance_usage_ratio,
        ]
        : [0, 0, 0, 0, 0];
      return option;
    });

    return () => (
      <div class={style.content}>
        <div class={style.chartAndStatisticsContainer}>
          <MyChart RadarData={radarData.value} />
          <Statistics data={statisticsList.value} />
          {
            filters.value.enterpriseName ? <PlateRankList /> : <EnterpriseRankList />
          }
        </div>
      </div>
    );
  },
});

/**
 * 雷达图
 */
const MyChart = defineComponent({
  props: {
    RadarData: {
      type: Object,
      required: true,
    },
  },
  setup(props) {
    /**
     * 绘制雷达图
     * 挂载时绘制
     * 数据改变时绘制
     */
    const chartDiv = ref<HTMLDivElement>();
    let radarChart: echarts.ECharts;
    const renderRadarChart = () => {
      if (chartDiv.value) {
        radarChart || (radarChart = echarts.init(chartDiv.value));
        props.RadarData && radarChart.setOption(props.RadarData);
      }
    };
    onMounted(() => {
      renderRadarChart();
    });
    watch(
      () => props.RadarData,
      () => {
        renderRadarChart();
      },
      { immediate: true }
    );

    return () => <div class={style.chart} ref={chartDiv}></div>;
  },
});

/**
 * 统计表
 */
const Statistics = defineComponent({
  props: {
    data: {
      type: Array as PropType<Statistics[]>,
      default: () => [],
    },
  },
  setup(props) {
    /**
     * class filter
     */
    const classFilter = (per: number) => {
      return per > 0 ? "up" : per === 0 || per === null ? "" : "down";
    };

    return () => (
      <div class={style.statistics}>
        <div class={style.part}>
          {props.data.slice(0, 2).map((item) => {
            return (
              <div class={item}>
                <div class={style.title}>{item.title}</div>
                <div class={style.value}>
                  <span class={style.count}>{item.count === null ? "- " : item.count}</span>
                  <span class={style.unit}>{item.unit}</span>
                </div>
                <div class={style.per}>
                  <span>{item.per ? "环比" : ""}</span>
                  <span class={[style.perCount, style[classFilter(item.per)]].join(" ")}>
                    {item.per === null ? "- " : item.per}%
                  </span>
                </div>
              </div>
            );
          })}
        </div>
        <div class={[style.part, style.event].join(" ")}>
          {props.data.slice(2).map((item) => {
            return (
              <div class={style.item}>
                <div class={style.title}>{item.title}</div>
                <div class={style.value}>
                  <span class={style.count}>{item.count === null ? "- " : item.count}</span>
                  <span class={style.unit}>{item.unit}</span>
                </div>
                <div class={style.per}>
                  <span>环比</span>
                  <span class={[style.perCount, style[classFilter(item.per)]].join(" ")}>
                    {item.per === null ? "- " : item.per}%
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    );
  },
});


/**
 * 企业报告信息
 */
const ReportInfo = defineComponent({
  setup() {
    const activeKey = ref<number>(1);
    const changeTab = (key: any) => {
      activeKey.value = key;
    }
    return () => (
      <div class={style.container}>
        <Tabs activeKey={activeKey.value} onChange={changeTab} type="card">
          <Tabs.TabPane key={1} tab={"泥头车管理"}>
            <div class={style.tabContainer}>
              <Header />
              <Body />
            </div>

          </Tabs.TabPane>
          <Tabs.TabPane key={2} tab={"设备管理"}>
            <div style="margin-top:30px;">
              <img src="/icon/devicePanel.png" style="width:100%;" />
            </div>
          </Tabs.TabPane>
        </Tabs>

      </div>
    );
  },
});

export default ReportInfo;
