<script setup lang="ts">
import { getOperatorAllListAPI } from "@/api/modules/system";
import { useSystemStore } from "@/store/modules/system";
import { getCentralControlBasicInfoByPageAPI, addCentralControlInfoAPI } from "@/api/modules/productionManagement";
import { AddCentralControlInfoParams } from "@/api/modules/productionManagement/types";
import { deepClone, dictTranslate } from "@/utils";

// 列表
const moduleList = ref([]);
const loading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showPageSize: true,
  showTotal: true
});

// 模态框
const open = ref<boolean>(false);
const system = useSystemStore();
const title = ref<string>("");
const operatorAllList = ref<any>([]);
const ecuBrandList = ref<any>([]);
const addFormRef = ref();
const addForm = ref<AddCentralControlInfoParams>({
  operatorId: "",
  ecuCode: "",
  ecuSn: "",
  ecuBrand: "",
  bindBattery: undefined
});
const rules = {
  ecuCode: [{ required: true, message: "请输入中控编号", trigger: "blur" }],
  ecuSn: [{ required: true, message: "请输入中控SN码", trigger: "blur" }],
  operatorId: [{ required: true, message: "请选择运营商", trigger: "change" }],
  ecuBrand: [{ required: true, message: "请选择中控品牌", trigger: "change" }],
  bindBattery: [{ required: true, message: "请选择是否绑定电池", trigger: "change" }]
};

const onAdd = () => {
  title.value = "新增组件";
  open.value = true;
};

const afterClose = () => {
  resetForm();
};

const resetForm = () => {
  addForm.value = {
    operatorId: "",
    ecuCode: "",
    ecuSn: "",
    ecuBrand: "",
    bindBattery: undefined
  };
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
};

const handleOk = async () => {
  let state = await addFormRef.value.validate();
  if (state) return false; // 校验不通过

  if (addForm.value.ecuId) {
    try {
      let res: any = await addCentralControlInfoAPI(addForm.value);
      if (res.code === 200) {
        arcoMessage("success", "修改成功");
        resetForm();
        getCentralControlBasicInfoByPage();
        return true;
      }
    } catch (error: any) {
      console.error(error);
      return false;
    }
  } else {
    try {
      let res: any = await addCentralControlInfoAPI(addForm.value);
      if (res.code === 200) {
        arcoMessage("success", "新增成功");
        resetForm();
        getCentralControlBasicInfoByPage();
        return true;
      }
    } catch (error: any) {
      console.error(error);
      return false;
    }
  }
};

//翻译字典值
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 {
      ecuBrandList.value = deepClone(system.getDictByCode("ecuBrandCode"));
      const res: any = await getOperatorAllListAPI();
      if (res.code === 200) {
        operatorAllList.value = res.data;
        resolve();
      }
    } catch (error) {
      console.error("获取运营商列表失败:", error);
      resolve();
    }
  });
};

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

const handlePageChange = (page: number) => {
  pagination.value.current = page;
  getCentralControlBasicInfoByPage();
};

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

onMounted(() => {
  getCentralControlBasicInfoByPage();
});
onBeforeMount(async () => {
  await getAllOperatorList();
});
</script>
<template>
  <div class="snow-page">
    <div class="snow-inner">
      <s-layout-tools>
        <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
        row-key="id"
        :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="中控SN码" data-index="ecuSn" align="center"></a-table-column>
          <a-table-column title="中控编号" data-index="ecuCode" 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="ecuBrand" align="center">
            <template #cell="{ record }">
              <span>{{ dictFormat(ecuBrandList, "dicValue", record.ecuBrand) }}</span>
            </template>
          </a-table-column>
          <a-table-column title="创建时间" data-index="createdAt" :width="180" align="center"></a-table-column>
          <!-- TUDO: 暂时不做操作功能 -->
          <!-- <a-table-column title="操作" :width="280" align="center" :fixed="'right'">
            <template #cell="{ record }">
              <a-space>
                <a-button type="primary" size="mini" :disabled="record.sysRole">
                  <template #icon><icon-edit /></template>
                  <span>修改</span>
                </a-button>
              </a-space>
            </template>
          </a-table-column> -->
        </template>
      </a-table>
    </div>
    <!-- 模态框 -->
    <a-modal v-model:visible="open" @close="afterClose" @before-ok="handleOk" @cancel="afterClose">
      <template #title> {{ title }} </template>
      <a-form ref="addFormRef" :model="addForm" :rules="rules" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
        <a-form-item field="ecuCode" label="中控编号" validate-trigger="blur">
          <a-input v-model="addForm.ecuCode" placeholder="请输入中控编号" />
        </a-form-item>
        <a-form-item field="ecuSn" label="中控SN码" validate-trigger="blur">
          <a-input v-model="addForm.ecuSn" placeholder="请输入中控SN码" />
        </a-form-item>
        <a-form-item field="operatorId" label="运营商">
          <a-select v-model="addForm.operatorId" placeholder="请选择运营商" validate-trigger="change">
            <a-option v-for="it in operatorAllList" :key="it.operatorId" :value="it.operatorId">{{ it.operatorName }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="ecuBrand" label="中控品牌">
          <a-select v-model="addForm.ecuBrand" placeholder="请选择中控品牌" validate-trigger="change">
            <a-option v-for="it in ecuBrandList" :key="it.dicId" :value="it.dicValue">{{ it.dicValueName }}</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="bindBattery" label="是否绑定电池">
          <a-radio-group v-model="addForm.bindBattery">
            <a-radio :value="true">是</a-radio>
            <a-radio :value="false">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<style lang="scss" scoped></style>
