<script lang="ts" setup>
import AddForm from "./component/addForm.vue";
import baseCostForm from "./component/baseCostForm.vue";
import periodCostForm from "./component/periodCostForm.vue";
import operationForm from "./component/operationForm.vue";
import {
  getRegionByPageAPI,
  addRegionAPI,
  deleteRegionAPI,
  updateRegionAPI,
  startRegionAPI,
  stopRegionAPI,
  saveRegionDefaultRuleAPI,
  getRegionDefaultRuleAPI,
  getRegionSpecialRuleAPI,
  updateRegionDefaultRuleAPI,
  getRegionOperationConfigAPI,
  saveRegionOperationConfigAPI
} from "@/api/modules/region";
import { deepClone, dictTranslate } from "@/utils";
import { useSystemStore } from "@/store/modules/system";
import { PointDataHandler } from "@/utils/map-tools";
import { getOperatorAllListAPI } from "@/api/modules/system";
import { Modal } from "@arco-design/web-vue";

// 列表
const form = ref<any>({
  regionSimpleName: "",
  regionName: ""
});

const system = useSystemStore();
const moduleList = ref<any>([]);
const regionStatusList = ref<any>([]);
const loading = ref<boolean>(false);
const tableRef = ref();
const AddFormRef = ref<any>(null);
const operatorAllList = ref<any>([]);
const title = ref<string>("");
const pagination = ref({
  pageNum: 1,
  total: 0,
  pageSize: 10,
  showPageSize: true,
  showTotal: true
});

onMounted(() => {
  getRegionByPage();
});
onBeforeMount(async () => {
  regionStatusList.value = deepClone(system.getDictByCode("regionStatus"));
  await getAllOperatorList();
});

const handlePageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize;
  pagination.value.pageNum = 1;
  getRegionByPage();
};

const handlePageChange = (page: number) => {
  pagination.value.pageNum = page;
  getRegionByPage();
};

const search = () => {
  pagination.value.pageNum = 1;
  getRegionByPage();
};
const reset = () => {
  form.value = {
    regionSimpleName: "",
    regionName: ""
  };
  search();
};
const onAdd = () => {
  open.value = true;
  title.value = "新增运营区";
};

const getRegionByPage = async () => {
  loading.value = true;
  try {
    const res: any = await getRegionByPageAPI({
      regionName: form.value.regionName,
      regionSimpleName: form.value.regionSimpleName,
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    });
    loading.value = false;
    if (res.code !== 200) {
      return;
    }
    const { records, pageNumber, pageSize } = res.data;
    pagination.value.pageNum = pageNumber;
    pagination.value.pageSize = pageSize;
    pagination.value.total = res.data.totalRow;
    moduleList.value = records;
  } catch (error) {
    console.error("获取列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// tag颜色
const tagColor = (record: any) => {
  const { status } = record;

  switch (status) {
    case 0:
      return "gray";
    case 1:
      return "red";
    case 2:
      return "green";
    default:
      return "gray";
  }
};

//翻译字典值
const dictFormat = (list: any[], key: string, value: string | number, valueKey: string = "dicValueName") => {
  return dictTranslate(list, key, value, valueKey);
};

// 获取所有运营商列表
const getAllOperatorList = async () => {
  return new Promise<void>(async resolve => {
    try {
      const res: any = await getOperatorAllListAPI();
      if (res.code === 200) {
        operatorAllList.value = res.data;
        resolve();
      }
    } catch (error) {
      console.error("获取运营商列表失败:", error);
      resolve();
    }
  });
};

// 删除运营区
const handleDelete = async (record: any) => {
  const { regionId } = record;
  try {
    const res: any = await deleteRegionAPI(regionId);
    if (res.code === 200) {
      arcoMessage("success", "删除成功");
      getRegionByPage();
    }
  } catch (error) {
    console.error("删除失败:", error);
  }
};

const handleSelect = (val: any, record: any) => {
  switch (val) {
    case "start":
      handleStart(record);
      break;
    case "stop":
      handleStop(record);
      break;
    case "baseCost":
      openBaseCostModal(record);
      break;
    case "periodCost":
      openPeriodCostModal(record);
      break;
    case "operation":
      openRegionConfigModal(record);
      break;
    default:
      break;
  }
};

// 开始运营
const handleStart = (record: any) => {
  const { regionId } = record;
  Modal.info({
    title: "开始运营",
    content: "请确认是否启动运营区开始运营？",
    hideCancel: false,
    closable: true,
    onBeforeOk: async () => {
      try {
        await startRegionAPI(regionId);
        arcoMessage("success", "启动成功");
        reset();
        return true;
      } catch (error) {
        console.error("启动运营区失败:", error);
        return false;
      }
    }
  });
};

// 停止运营
const handleStop = (record: any) => {
  const { regionId } = record;
  Modal.error({
    title: "停止运营",
    content: "请确认是否停止运营区运营？",
    hideCancel: false,
    closable: true,
    onBeforeOk: async () => {
      try {
        await stopRegionAPI(regionId);
        arcoMessage("success", "停止成功");
        reset();
        return true;
      } catch (error) {
        console.error("停止运营区失败:", error);
        return false;
      }
    }
  });
};

/**
 *新增模态框
 **/
const open = ref<boolean>(false);
const afterClose = () => {
  resetForm();
};

// 修改运营区
const handleUpdate = (record: any) => {
  open.value = true;
  title.value = "修改运营区";
  const data = deepClone(record);
  data.coordinates = PointDataHandler.restoreForDisplay(data.regionPolygon.coordinates);
  AddFormRef.value.updateForm(data);
};

// 格式化上传数据
const formatData = (data: any, type: string = "add") => {
  if (type === "add") {
    const regionPolygon: any = {
      type: "Polygon",
      coordinates: []
    };
    regionPolygon.coordinates = PointDataHandler.prepareForUpload(data.coordinates);

    return {
      operatorId: data.operatorId,
      regionName: data.regionName,
      regionId: data.regionId ? data.regionId : "",
      regionSimpleName: data.regionSimpleName,
      regionPolygon
    };
  }

  if (type === "edit") {
  }
};

// 重置表单
const resetForm = () => {
  open.value = false;
  AddFormRef.value?.resetForm();
};

// 新增提交
const handleOk = async () => {
  const { status, data } = await AddFormRef.value?.submit();
  if (status) return false;

  try {
    const parmas = formatData(data, "add");

    if (!parmas) {
      arcoMessage("error", "数据格式有误");
      return false;
    }

    if (data.regionId) {
      await updateRegionAPI(parmas);
    } else {
      await addRegionAPI(parmas);
    }

    arcoMessage("success", data.regionId ? "修改成功" : "新增成功");
    resetForm();
    getRegionByPage();

    return false;
  } catch (error) {
    console.error(error);
    return false;
  }
};

/**
 *基本费用配置模态框
 **/
const openBaseCost = ref<boolean>(false);
const baseCostFormRef = ref<any>(null);

const openBaseCostModal = async (record: any) => {
  // 获取默认规则
  try {
    const res: any = await getRegionDefaultRuleAPI(record.regionId);
    if (res.code === 200) {
      openBaseCost.value = true;
      baseCostFormRef.value.setFormData(res.data, record.regionId);
    }
  } catch (error) {
    console.error("获取默认规则失败:", error);
  }
};

const handleBaseCost = async () => {
  const { status, data } = await baseCostFormRef.value?.validateForm();
  console.log("验证结果:", status, data);
  if (!status) return false;
  try {
    await saveRegionDefaultRuleAPI(data);
    baseCostFormRef.value?.clearForm();
    arcoMessage("success", "保存成功");
    openBaseCost.value = false;
    return true;
  } catch (error) {
    console.error("保存默认规则失败:", error);
  }
};
// 关闭基本费用配置模态框
const BaseCostClose = () => {
  openBaseCost.value = false;
  baseCostFormRef.value?.clearForm();
};

/**
 *高峰费用配置模态框
 **/
const openPeriodCost = ref<boolean>(false);
const periodCostFormRef = ref<any>(null);
const PeriodCostClose = () => {
  openPeriodCost.value = false;
  periodCostFormRef.value?.clearForm();
};
const openPeriodCostModal = async (record: any) => {
  try {
    const res: any = await getRegionSpecialRuleAPI(record.regionId);
    if (res.code === 200) {
      openPeriodCost.value = true;
      periodCostFormRef.value?.setFormData({
        data: res.data,
        regionId: record.regionId
      });
    }
  } catch (error) {
    console.error("获取基础配置规则失败:", error);
  }
};

// 高峰费用配置
const handlePeriodCost = async () => {
  const { status, data } = await periodCostFormRef.value?.validateForm();
  console.log(data);
  if (!status) return false;
  try {
    await updateRegionDefaultRuleAPI(data);
    periodCostFormRef.value?.clearForm();
    arcoMessage("success", "保存成功");
    openPeriodCost.value = false;
    return true;
  } catch (error) {
    console.error("高峰配置失败:", error);
  }
};

/**
 *运营配置模态框
 **/
const openRegionConfig = ref<boolean>(false);
const regionConfigFormRef = ref<any>(null);
const RegionConfigClose = () => {
  openRegionConfig.value = false;
  regionConfigFormRef.value?.resetForm();
};
const openRegionConfigModal = async (record: any) => {
  try {
    const res = await getRegionOperationConfigAPI(record.regionId);
    openRegionConfig.value = true;
    regionConfigFormRef.value?.setFormData(res.data);
  } catch (error) {
    console.error("获取运营配置失败:", error);
  }
};
const handleRegionConfig = async () => {
  const { status, data } = await regionConfigFormRef.value?.validateForm();
  console.log(data);
  if (!status) return false;
  try {
    await saveRegionOperationConfigAPI(data);
    regionConfigFormRef.value?.resetForm();
    arcoMessage("success", "保存成功");
    openRegionConfig.value = false;
    return true;
  } catch (error) {
    console.error("运营配置保存失败:", error);
    return false;
  }
};
</script>

<template>
  <div class="snow-page">
    <div class="snow-inner">
      <s-layout-tools>
        <template #left>
          <a-space wrap>
            <a-input v-model="form.regionName" placeholder="运营区名称" allow-clear />
            <a-input v-model="form.regionSimpleName" placeholder="运营区简称" allow-clear />
            <a-button type="primary" @click="search">
              <template #icon><icon-search /></template>
              <span>查询</span>
            </a-button>
            <a-button @click="reset">
              <template #icon><icon-refresh /></template>
              <span>重置</span>
            </a-button>
          </a-space>
        </template>
        <template #right>
          <a-space wrap>
            <a-button type="primary" @click="onAdd">
              <template #icon><icon-plus /></template>
              <span>新增</span>
            </a-button>
          </a-space>
        </template>
      </s-layout-tools>
      <a-table
        ref="tableRef"
        row-key="batteryId"
        :data="moduleList"
        :bordered="{ cell: true }"
        :loading="loading"
        :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
        :pagination="pagination"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #columns>
          <a-table-column title="序号" :width="60" align="center">
            <template #cell="cell">
              <span>{{ (pagination.pageNum - 1) * pagination.pageSize + cell.rowIndex + 1 }}</span>
            </template>
          </a-table-column>
          <a-table-column title="运营区名称" data-index="regionName" align="center"></a-table-column>
          <a-table-column title="运营区简称" data-index="regionSimpleName" align="center"></a-table-column>
          <a-table-column title="运营商" data-index="operatorId" align="center">
            <template #cell="{ record }">
              <span>{{ dictFormat(operatorAllList, "operatorId", record.operatorId, "operatorName") }}</span>
            </template>
          </a-table-column>
          <a-table-column title="状态" data-index="status" align="center">
            <template #cell="{ record }">
              <a-tag :color="tagColor(record)" bordered>{{ dictFormat(regionStatusList, "dicValue", record.status) }}</a-tag>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createdAt" align="center"></a-table-column>
          <a-table-column title="操作" align="center" :fixed="'right'">
            <template #cell="{ record }">
              <a-space wrap>
                <a-button type="primary" size="mini" @click="handleUpdate(record)" :disabled="record.status === 1">
                  <template #icon><icon-link /></template>
                  <span>修改</span>
                </a-button>
                <a-popconfirm type="warning" content="确定删除该运营区?" @ok="handleDelete(record)">
                  <a-button type="primary" status="danger" size="mini" :disabled="record.status === 1">
                    <template #icon><icon-delete /></template>
                    <span>删除</span>
                  </a-button>
                </a-popconfirm>
                <a-dropdown @select="(v: any) => handleSelect(v, record)">
                  <a-button size="mini" type="primary">
                    更多
                    <template #icon><icon-down /></template>
                  </a-button>
                  <template #content>
                    <a-doption value="start" :disabled="record.status === 1">开始运营</a-doption>
                    <a-doption value="stop" :disabled="record.status !== 1">停止运营</a-doption>
                    <a-doption value="baseCost" :disabled="record.status === 1">基本费用配置</a-doption>
                    <a-doption value="periodCost" :disabled="record.status === 1">高峰费用配置</a-doption>
                    <a-doption value="operation" :disabled="record.status === 1">运营配置</a-doption>
                  </template>
                </a-dropdown>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
    <!-- 新增 -->
    <a-modal v-model:visible="open" @close="afterClose" @before-ok="handleOk" @cancel="afterClose" :width="700">
      <template #title> {{ title }} </template>
      <AddForm ref="AddFormRef" :operatorList="operatorAllList" />
    </a-modal>
    <!-- 基本费用配置 -->
    <a-modal
      v-model:visible="openBaseCost"
      @close="BaseCostClose"
      @before-ok="handleBaseCost"
      @cancel="BaseCostClose"
      :width="800"
      okText="保存"
    >
      <template #title> 基本费用配置 </template>
      <baseCostForm ref="baseCostFormRef" />
    </a-modal>
    <!-- 高峰费用配置 -->
    <a-modal
      v-model:visible="openPeriodCost"
      @close="PeriodCostClose"
      @before-ok="handlePeriodCost"
      @cancel="PeriodCostClose"
      :width="1200"
      okText="保存"
    >
      <template #title> 高峰费用配置 </template>
      <periodCostForm ref="periodCostFormRef" />
    </a-modal>

    <!-- 运营配置 -->
    <a-modal
      v-model:visible="openRegionConfig"
      @close="RegionConfigClose"
      :body-style="{
        maxHeight: 'calc(100vh - 300px)',
        overflowY: 'auto'
      }"
      @before-ok="handleRegionConfig"
      @cancel="RegionConfigClose"
      :width="1100"
      okText="保存"
    >
      <template #title> 运营相关配置 </template>
      <operationForm ref="regionConfigFormRef" />
    </a-modal>
  </div>
</template>

<style lang="scss" scoped></style>
