<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="充电站ID" prop="stationId">
          <el-input
            v-model="queryParams.stationId"
            placeholder="请输入充电站ID"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="充电站名称" prop="stationName">
          <el-input
            v-model="queryParams.stationName"
            placeholder="请输入充电站名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="站点状态" prop="stationStatus">
          <el-select
            v-model="queryParams.stationStatus"
            placeholder="请选择站点状态"
            clearable
            style="width: 200px"
          >
            <el-option label="未知" :value="0" />
            <el-option label="建设中" :value="1" />
            <el-option label="关闭下线" :value="5" />
            <el-option label="维护中" :value="6" />
            <el-option label="正常使用" :value="50" />
          </el-select>
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="stationId"
          label="充电站ID"
          prop="stationId"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="equipmentOwnerId"
          label="设备所属方"
          prop="equipmentOwnerName"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            {{ scope.row.equipmentOwnerName ? scope.row.equipmentOwnerName : "--" }}
          </template>
        </el-table-column>
        <el-table-column
          key="stationName"
          label="充电站名称"
          prop="stationName"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="address"
          label="详细地址"
          prop="address"
          min-width="150"
          align="center"
        />
        <el-table-column
          key="serviceTel"
          label="服务电话"
          prop="serviceTel"
          min-width="150"
          align="center"
        />
        <!--        1-公共,50-个人,100-公交(专用),101-环卫(专用),102-物流(专用),103-出租车(专用),255-其他-->
        <el-table-column
          key="stationType"
          label="站点类型"
          prop="stationType"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.stationType === 1" type="primary">公共</el-tag>
            <el-tag v-if="scope.row.stationType === 50" type="danger">个人</el-tag>
            <el-tag v-if="scope.row.stationType === 100" type="info">公交(专用)</el-tag>
            <el-tag v-if="scope.row.stationType === 101" type="primary">环卫(专用)</el-tag>
            <el-tag v-if="scope.row.stationType === 102" type="success">物流(专用)</el-tag>
            <el-tag v-if="scope.row.stationType === 103" type="warning">物流(专用)</el-tag>
            <el-tag v-if="scope.row.stationType === 255" type="info">物流(专用)</el-tag>
          </template>
        </el-table-column>
        <!--        0-未知,1-建设中,5-关闭下线,6-维护中,50-正常使用-->
        <el-table-column
          key="stationStatus"
          label="站点状态"
          prop="stationStatus"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.stationStatus === 0" type="warning">未知</el-tag>
            <el-tag v-if="scope.row.stationStatus === 1" type="danger">建设中</el-tag>
            <el-tag v-if="scope.row.stationStatus === 5" type="info">关闭下线</el-tag>
            <el-tag v-if="scope.row.stationStatus === 6" type="primary">维护中</el-tag>
            <el-tag v-if="scope.row.stationStatus === 50" type="success">正常使用</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          key="updateTime"
          label="更新时间"
          prop="updateTime"
          min-width="150"
          align="center"
        />
        <el-table-column label="操作" align="center" width="300">
          <template #default="scope">
            <el-button type="primary" icon="edit" size="small" @click="handleOpenDialog(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>
    <el-drawer v-model="drawer" :direction="direction" title="详情编辑">
      <el-form
        ref="dataFormRef"
        :model="formDataInfo"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="站点名称" prop="stationName">
          <el-input v-model="formDataInfo.stationName" disabled />
        </el-form-item>
        <el-form-item label="站点营业时间" prop="ownBusinessHours">
          <el-input v-model="formDataInfo.ownBusinessHours" disabled />
        </el-form-item>
        <el-form-item label="站点轮播图" prop="bannerPictures">
          <MultiImageUpload
            v-model="bannerPicturesRef"
            @update:model-value="
              () => {
                // 手动触发表单验证
                if (dataFormRef.value) {
                  dataFormRef.value.validateField('bannerPictures');
                }
              }
            "
          ></MultiImageUpload>
        </el-form-item>
        <el-form-item label="站点提示语" prop="stationTips">
          <el-input v-model="formDataInfo.stationTips" />
        </el-form-item>
<!--        prop="customerServiceHotline"-->
        <el-form-item label="站点联系电话">
          <el-input v-model="formDataInfo.customerServiceHotline" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
defineOptions({
  name: "ThirdPartyStationInfo",
  inheritAttrs: false,
});

import ThirdPartyStationInfoAPI, {
  ThirdPartyStationInfoPageVO,
  ThirdPartyStationInfoForm,
  ThirdPartyStationInfoPageQuery,
} from "@/api/equipmentManage/third-party-station-info-api";
// 导入MultiImageUpload组件
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<ThirdPartyStationInfoPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 第三方充电站信息表格数据
const pageData = ref<ThirdPartyStationInfoPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 第三方充电站信息表单数据
const formData = reactive<ThirdPartyStationInfoForm>({});

/** 查询第三方充电站信息 */
function handleQuery() {
  loading.value = true;
  ThirdPartyStationInfoAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置第三方充电站信息查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

const drawer = ref(false);
const formDataInfo = ref({});
const direction = ref("rtl");

// 添加表单验证规则
const formRules = {
  stationTips: [{ required: true, message: "站点提示语不能为空", trigger: "blur" }],
  // customerServiceHotline: [{ required: true, message: "站点联系电话不能为空", trigger: "blur" }],
};

// 定义轮播图引用
const bannerPicturesRef = ref();

/** 打开第三方充电站信息弹窗 */
function handleOpenDialog(row?: any) {
  drawer.value = true;
  // 清空之前的轮播图数据
  bannerPicturesRef.value = [];
  ThirdPartyStationInfoAPI.getFormData(parseInt(row.id)).then((data) => {
    formDataInfo.value = data;
    if (data.bannerPictures && Array.isArray(data.bannerPictures)) {
      bannerPicturesRef.value = data.bannerPictures;
    } else {
      bannerPicturesRef.value = [];
    }
  });
}

/** 点击确认按钮 */
function confirmClick() {
  // 验证表单
  dataFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 构造提交数据
      const submitData = {
        id: formDataInfo.value.id, // 站点id
        stationTips: formDataInfo.value.stationTips, // 站点提示语
        customerServiceHotline: formDataInfo.value.customerServiceHotline || "", // 站点联系电话，表单没返则为空
        bannerPictures: bannerPicturesRef.value || [], // 站点banner图，格式为['图片链接','图片链接','图片链接']
      };

      // 调用stationUpdate接口方法进行提交
      loading.value = true;
      ThirdPartyStationInfoAPI.stationUpdate(submitData)
        .then(() => {
          ElMessage.success("保存成功");
          drawer.value = false;
          handleQuery(); // 重新查询数据
        })
        .catch((error: any) => {
          ElMessage.error("保存失败: " + error.message);
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

/** 提交第三方充电站信息表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ThirdPartyStationInfoAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        ThirdPartyStationInfoAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭第三方充电站信息弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除第三方充电站信息 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      ThirdPartyStationInfoAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
