<script lang="ts" setup>
import { ref, reactive, onMounted, watchEffect } from 'vue';
import TrendCard from './components/TrendCard.vue';
import SimpleCard from './components/SimpleCard.vue';
import Divider from './components/Divider.vue';
import AIChat from './components/AIChat.vue';
import Echarts from '@/components/ReEcharts/index.vue';
import { EChartsOption, use } from 'echarts';
import { dayjs } from 'element-plus';
import { QuestionFilled } from '@element-plus/icons-vue';
import { useStore } from "../../store/index"
const { userInfo } = useStore()
import {
  getSummaryData,
  getBulletinData,
  BulletinData,
  getStageData,
  RequestProps,
  StageData,
  SummaryData
} from './api';

const dataAnalysisFlag = userInfo?.moduleList?.filter((item: any) => item.path == '/analysis') || []
const isExistBusiness = sessionStorage.getItem("isExistBusiness");
const businessLabel = isExistBusiness === "1" ? "商机" : "项目"; 
const isSimple = sessionStorage.getItem("isSimple");
const permissionOptions = dataAnalysisFlag.length > 0 ? [
  {
    label: '仅本人',
    value: 0
  },
  {
    label: '本人及下属',
    value: 1
  },
  {
    label: '仅本部门',
    value: 2
  },
  {
    label: '本部门及下属部门',
    value: 3
  }
] : [{
    label: '仅本人',
    value: 0
  },]
const dateOptions = [
  {
    label: '本月',
    value: 0
  },
  {
    label: '本周',
    value: 1
  },
  {
    label: '本年',
    value: 2
  }
];

type PromptType = {
  permission?: 0 | 1 | 2 | 3;
  date?: 0 | 1 | 2 | any;
  sliceDate: [Date, Date];
};

const select1 = ref<HTMLDivElement>();
const select2 = ref<HTMLDivElement>();
const select3 = ref<HTMLDivElement>();

const getFirstDayOfMonth = () => {
  const now = new Date();
  return new Date(now.getFullYear(), now.getMonth(), 1);
};

const bulletinPrompt = reactive<PromptType>({
  permission: 0,
  date: 0,
  sliceDate: [getFirstDayOfMonth(), new Date()]
});
const summaryPrompt = reactive<PromptType>({
  permission: 0,
  date: 0,
  sliceDate: [getFirstDayOfMonth(), new Date()]
});
const stagePrompt = reactive<PromptType>({
  permission: 0,
  date: 0,
  sliceDate: [getFirstDayOfMonth(), new Date()]
});

const requestData = reactive<{
  bulletin: BulletinData['data'] | null;
  summary: SummaryData['data'] | null;
  stage: StageData['data'] | null;
}>({
  summary: null,
  stage: null,
  bulletin: null
});

const chartOptions: EChartsOption = reactive({
  grid: { top: 0, bottom: 20, left: 60 },
  yAxis: {
    type: 'category',
    axisLabel: {
      formatter: (value: string) => {
        return value.replace(/(.{4})/g, "$1\n");
      },
    },
  },
  xAxis: {
    type: 'value'
  },
  series: [
    {
      barWidth: 20,
      data: [10, 30, 30, 30, 30],
      type: 'bar'
    }
  ]
});

const queryBulletin = async (payload?: RequestProps) => {
  const bulletinResult = await getBulletinData(payload);
  requestData.bulletin = bulletinResult.data;
};

const querySummary = async (payload?: RequestProps) => {
  const summaryResult = await getSummaryData(payload);
  requestData.summary = summaryResult.data;
};

const queryStage = async (payload?: RequestProps) => {
  const stageResult = await getStageData(payload);
  const data = stageResult.data;

  // @ts-ignore
  chartOptions.yAxis.data = data.dataMap.map((map) => map.stageName);
  // @ts-ignore
  chartOptions.series[0].data = data.dataMap.map((map) => map.num);
};

watchEffect(() => {
  queryBulletin({
    ...(bulletinPrompt.date === ('ignore' as any)
      ? {
          startDate: dayjs(bulletinPrompt.sliceDate[0]).format('YYYY-MM-DD'),
          endDate: dayjs(bulletinPrompt.sliceDate[1]).format('YYYY-MM-DD')
        }
      : { dateType: bulletinPrompt.date }),
    queryType: bulletinPrompt.permission
  });
});

watchEffect(() => {
  queryStage({
    ...(stagePrompt.date === ('ignore' as any)
      ? {
          startDate: dayjs(stagePrompt.sliceDate[0]).format('YYYY-MM-DD'),
          endDate: dayjs(stagePrompt.sliceDate[1]).format('YYYY-MM-DD')
        }
      : { dateType: stagePrompt.date }),
    queryType: stagePrompt.permission
  });
});

watchEffect(() => {
  querySummary({
    ...(summaryPrompt.date === ('ignore' as any)
      ? {
          startDate: dayjs(summaryPrompt.sliceDate[0]).format('YYYY-MM-DD'),
          endDate: dayjs(summaryPrompt.sliceDate[1]).format('YYYY-MM-DD')
        }
      : { dateType: summaryPrompt.date }),
    queryType: summaryPrompt.permission
  });
});

watchEffect(() => {
  console.log(bulletinPrompt.date, '-----', bulletinPrompt.sliceDate, '88888888---watchEffect');
});
</script>

<template>
  <div class="m-5 min-h-full">
    <section class="flex gap-4">
      <!-- Left side - Original functionality -->
      <div class="w-1/2 min-w-[650px] flex-shrink-0 bg-white p-4 rounded">
        <div class="flex gap-3 mb-4">
          <div class="w-40">
            <el-select
              size="small"
              :model-value="bulletinPrompt.permission"
              @change="(value: any) => (bulletinPrompt.permission = value)"
            >
              <el-option
                v-for="permission in permissionOptions"
                :label="permission.label"
                :value="permission.value"
              />
            </el-select>
          </div>
          <div class="w-40">
            <el-select
              ref="select1"
              size="small"
              :model-value="bulletinPrompt.date"
              @change="(value: any) => (bulletinPrompt.date = value)"
            >
              <el-option v-for="date in dateOptions" :label="date.label" :value="date.value" />
              <el-option label="自定义" value="ignore" disabled>
                <div class="flex gap-2 w-80">
                      <el-date-picker
                        size="small"
                        :clearable="false"
                        type="daterange"
                        class="w-40"
                        v-model="bulletinPrompt.sliceDate"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                      />
                  <el-button
                    size="small"
                    type="primary"
                    @click="
                      () => {
                        select1?.blur();
                        bulletinPrompt.date = 'ignore';
                      }
                    "
                    >确认</el-button
                  >
                </div>
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="border-gray-200 border rounded p-3">
          <div class="flex gap-1.5 items-center mb-3">
            <img width="16" src="../../assets/trend.png" />
            <div class="text-sm font-medium">销售简报</div>
            <el-icon><QuestionFilled class="text-gray-500 text-sm" /></el-icon>
          </div>
          <div class="grid xl:grid-cols-4 lg:grid-cols-3 grid-cols-2 gap-4">
            <TrendCard
              title="新增客户"
              unit="人"
              :selectVal="bulletinPrompt"
              :number="requestData?.bulletin?.custom.customCount"
              :compare="requestData?.bulletin?.custom.customPromote"
            />
            <TrendCard
              title="新增联系人"
              unit="人"
              :selectVal="bulletinPrompt"
              :number="requestData?.bulletin?.contacts.contactsCount"
              :compare="requestData?.bulletin?.contacts.contactsPromote"
              v-if="isSimple != '1'"
            />
            <TrendCard
              :title="`新增${businessLabel}`"
              unit="个"
              :selectVal="bulletinPrompt"
              :number="requestData?.bulletin?.businessOpportunity.businessOpportunityCount"
              :compare="requestData?.bulletin?.businessOpportunity.businessOpportunityPromote"
            />
            <TrendCard
              title="新增销售订单"
              unit="个"
              :selectVal="bulletinPrompt"
              :number="requestData?.bulletin?.salesOrder.salesOrderCount"
              :compare="requestData?.bulletin?.salesOrder.salesOrderPromote"
              v-if="isSimple != '1'"
            />
            <TrendCard
              title="销售订单金额"
              unit="元"
              :selectVal="bulletinPrompt"
              :number="requestData?.bulletin?.salesOrdersPrice.salesOrdersPrice"
              :compare="requestData?.bulletin?.salesOrdersPrice.salesOrderPricePromote"
              v-if="isSimple != '1'"
            />
            <TrendCard
              :title="`${businessLabel}金额`"
              unit="元"
              :selectVal="bulletinPrompt"
              :number="requestData?.bulletin?.businessOpportunityPrice.businessOpportunityPrice"
              :compare="requestData?.bulletin?.businessOpportunityPrice.businessOpportunityPromote"
            />
            <TrendCard
              title="新增线索"
              unit="个"
              :selectVal="bulletinPrompt"
              :number="requestData?.bulletin?.clue.clueCount"
              :compare="requestData?.bulletin?.clue.cluePromote"
            />
          </div>
        </div>
        <div class="my-8 flex gap-4 items-start">
          <div class="border-gray-200 border rounded p-3 flex-1">
            <div class="text-sm font-medium">数据汇总</div>
            <div class="flex gap-3 mb-8 mt-2">
              <div class="w-40">
                <el-select
                  clearable
                  size="small"
                  :model-value="summaryPrompt.permission"
                  @change="(value: any) => (summaryPrompt.permission = value)"
                >
                  <el-option
                    v-for="permission in permissionOptions"
                    :label="permission.label"
                    :value="permission.value"
                  />
                </el-select>
              </div>
              <div class="w-40">
                <el-select
                  ref="select2"
                  clearable
                  size="small"
                  :model-value="summaryPrompt.date"
                  @change="(value: any) => (summaryPrompt.date = value)"
                >
                  <el-option v-for="date in dateOptions" :label="date.label" :value="date.value" />
                  <el-option label="自定义" value="ignore" disabled>
                    <div class="flex gap-2 w-80">
                      <el-date-picker
                        size="small"
                        :clearable="false"
                        type="daterange"
                        class="w-40"
                        v-model="summaryPrompt.sliceDate"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                      />
                      <el-button
                        size="small"
                        type="primary"
                        @click="
                          () => {
                            select2?.blur();
                            summaryPrompt.date = 'ignore';
                          }
                        "
                        >确认</el-button
                      >
                    </div>
                  </el-option>
                </el-select>
              </div>
            </div>
            <Divider title="客户汇总" />
            <div class="my-6 grid grid-cols-4 gap-2">
              <SimpleCard
                title="新增客户"
                unit="个"
                :number="requestData.summary?.customDataSummary.newNum"
              />
              <SimpleCard
                title="转成交客户"
                unit="个"
                :number="requestData.summary?.customDataSummary.closeDealNum"
                v-if="false"
              />
            </div>
            <Divider :title="`${businessLabel}汇总`" />
            <div class="my-6 grid grid-cols-4 gap-2">
              <SimpleCard
                :title="`新增${businessLabel}`"
                unit="个"
                :number="requestData.summary?.businessOpportunityDataSummary.newNum"
              />
              <SimpleCard
                :title="`赢单${businessLabel}`"
                unit="个"
                :number="requestData.summary?.businessOpportunityDataSummary.winning"
              />
              <SimpleCard
                :title="`输单${businessLabel}`"
                unit="个"
                :number="requestData.summary?.businessOpportunityDataSummary.losting"
              />
              <SimpleCard
                :title="`${businessLabel}总金额`"
                unit="元"
                :number="requestData.summary?.businessOpportunityDataSummary.allAmountOfMoney"
              />
            </div>
            <Divider title="线索汇总" />
            <div class="my-6 grid grid-cols-4 gap-2">
              <SimpleCard
                title="新增线索"
                unit="个"
                :number="requestData.summary?.clueDataSummary.newNum"
              />
              <SimpleCard
                :title="`线索转${businessLabel}`"
                unit="个"
                :number="requestData.summary?.clueDataSummary.changeNum"
              />
            </div>
          </div>
          <div class="border-gray-200 border rounded p-3 flex-1">
            <div class="text-sm font-medium">{{ `${businessLabel}阶段` }}</div>
            <div class="flex gap-3 mb-8 mt-2">
              <div class="w-40">
                <el-select
                  clearable
                  size="small"
                  :model-value="stagePrompt.permission"
                  @change="(value: any) => (stagePrompt.permission = value)"
                >
                  <el-option
                    v-for="permission in permissionOptions"
                    :label="permission.label"
                    :value="permission.value"
                  />
                </el-select>
              </div>
              <div class="w-40">
                <el-select
                  ref="select3"
                  clearable
                  size="small"
                  :model-value="stagePrompt.date"
                  @change="(value: any) => (stagePrompt.date = value)"
                >
                  <el-option v-for="date in dateOptions" :label="date.label" :value="date.value" />
                  <el-option label="自定义" value="ignore" disabled>
                    <div class="flex gap-2 w-80">
                      <el-date-picker
                        size="small"
                        :clearable="false"
                        type="daterange"
                        class="w-40"
                        v-model="stagePrompt.sliceDate"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                      />
                      <el-button
                        size="small"
                        type="primary"
                        @click="
                          () => {
                            select3?.blur();
                            stagePrompt.date = 'ignore';
                          }
                        "
                        >确认</el-button
                      >
                    </div>
                  </el-option>
                </el-select>
              </div>
            </div>
            <div class="h-60">
              <Echarts :option="chartOptions"></Echarts>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Right side - AI Chat -->
      <div class="w-1/2 bg-white p-4 rounded">
        <AIChat />
      </div>
    </section>
  </div>
</template>
