<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="客户编号" prop="customerNo">
              <el-input v-model="queryParams.customerNo" placeholder="请输入客户编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerNo">
              <el-input v-model="queryParams.customerNo" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="申请状态" prop="serviceTime">
              <el-select v-model="queryParams.serviceTime" placeholder="请选择服务时长" clearable>
                <el-option v-for="dict in service_time_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="开始时间" prop="serviceStartTime">
              <el-date-picker
                clearable
                v-model="queryParams.serviceStartTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择服务开始时间"
              />
            </el-form-item>
            <el-form-item label="开始时间" prop="serviceEndTime">
              <el-date-picker clearable v-model="queryParams.serviceEndTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择服务开始时间" />
            </el-form-item>
            <el-form-item label="技术顾问" prop="technicalAdviser">
              <el-input v-model="queryParams.technicalAdviser" placeholder="请输入技术顾问姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="20"><span>维保客户信息列表</span> </el-col>
          <el-col :span="1.5">
            <el-button style="float: right" type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['customer:maintainInfo:add']"
              >新增维保</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              style="float: right"
              type="primary"
              plain
              icon="User"
              @click="handleAllotAdviser()"
              v-hasPermi="['customer:maintainInfo:allot']"
              >分配技术顾问</el-button
            >
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="maintainInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="企业名称" align="center" prop="customerName" />
        <el-table-column label="维保类型" align="center" prop="maintainType">
          <template #default="scope">
            <dict-tag :options="maintenance_type" :value="scope.row.maintainType" />
          </template>
        </el-table-column>
        <el-table-column label="起始时间" align="center" prop="serviceStartTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.serviceStartTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="serviceEndTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.serviceEndTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="维保次数限制" align="center" prop="maintenLimit" />
        <el-table-column label="维保次数" align="center" prop="maintainCount" />
        <el-table-column label="主要技术顾问" align="center" prop="technicalAdviser" />
        <el-table-column label="主要维保项目" align="center" prop="serviceContentStr"> </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="User" @click="handleAllotAdviser(scope.row)" v-hasPermi="['customer:maintainInfo:add']"
              >分配技术顾问</el-button
            >
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['customer:maintainInfo:edit']">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 分配技术顾问对话框 -->
    <allot-technical-adviser-dialog v-model="allotDialogVisible" :edit-data="currentAdviserData" @confirm="handleAllotConfirm" />
  </div>
</template>

<script setup name="MaintainInfo" lang="ts">
import {
  listMaintainInfo,
  getMaintainInfo,
  delMaintainInfo,
  addMaintainInfo,
  updateMaintainInfo,
  allotTechnicalAdviser
} from '@/api/customer/maintainInfo';
import { MaintainInfoVO, MaintainInfoQuery, MaintainInfoForm, AllotTechnicalAdviserForm } from '@/api/customer/maintainInfo/types';
import AllotTechnicalAdviserDialog from './dialog/allotTechnicalAdviser.vue';
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { service_content, service_time_type, maintenance_type, sys_normal_disable } = toRefs<any>(
  proxy?.useDict('service_content', 'service_time_type', 'maintenance_type', 'sys_normal_disable')
);

const maintainInfoList = ref<MaintainInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const maintainInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 分配技术顾问对话框
const allotDialogVisible = ref(false);
const currentAdviserData = ref<any>(null);
const currentMaintainId = ref<string | number>();

const initFormData: MaintainInfoForm = {
  id: undefined,
  customerId: undefined,
  maintainNo: undefined,
  customerNo: undefined,
  applicantName: undefined,
  applicantPhone: undefined,
  serviceTime: undefined,
  monthMainten: undefined,
  remainingMainten: undefined,
  maintenLimit: undefined,
  serviceContent: [],
  otherService: undefined,
  serviceStartTime: undefined,
  serviceEndTime: undefined,
  maintainStatus: undefined,
  serviceEngineerId: undefined,
  serviceEngineer: undefined,
  engineerPhone: undefined,
  technicalAdviserId: undefined,
  technicalAdviser: undefined,
  technicalAdviserPhone: undefined,
  maintainFile: undefined,
  maintainType: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<MaintainInfoForm, MaintainInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerId: undefined,
    maintainNo: undefined,
    customerNo: undefined,
    applicantName: undefined,
    applicantPhone: undefined,
    serviceTime: undefined,
    monthMainten: undefined,
    remainingMainten: undefined,
    maintenLimit: undefined,
    serviceContent: undefined,
    otherService: undefined,
    serviceStartTime: undefined,
    serviceEndTime: undefined,
    maintainStatus: undefined,
    serviceEngineerId: undefined,
    serviceEngineer: undefined,
    engineerPhone: undefined,
    technicalAdviserId: undefined,
    technicalAdviser: undefined,
    technicalAdviserPhone: undefined,
    maintainFile: undefined,
    maintainType: undefined,
    status: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询维保记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await listMaintainInfo(queryParams.value);
  maintainInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  maintainInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: MaintainInfoVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({
    path: '/customer/increment-add'
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: MaintainInfoVO) => {
  const _id = row?.id || ids.value[0];
  router.push({
    path: '/customer/increment-add',
    query: { id: _id, status: 'edit' }
  });
};

/** 提交按钮 */
const submitForm = () => {
  maintainInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateMaintainInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addMaintainInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: MaintainInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除维保记录编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delMaintainInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/maintainInfo/export',
    {
      ...queryParams.value
    },
    `maintainInfo_${new Date().getTime()}.xlsx`
  );
};

/** 打开分配技术顾问对话框 */
const handleAllotAdviser = (row?: MaintainInfoVO) => {
  if (row) {
    // 单行操作
    currentMaintainId.value = row.id;
    currentAdviserData.value = {
      technicalAdviserId: row.technicalAdviserId,
      contactPhone: row.technicalAdviserPhone
    };
  } else {
    // 批量操作
    if (ids.value.length === 0) {
      proxy?.$modal.msgWarning('请选择要分配技术顾问的维保记录');
      return;
    }
    currentMaintainId.value = undefined;
    currentAdviserData.value = null;
  }
  allotDialogVisible.value = true;
};

/** 确认分配技术顾问 */
const handleAllotConfirm = async (data: any) => {
  try {
    // 单行操作
    if (currentMaintainId.value) {
      const params: AllotTechnicalAdviserForm = {
        id: currentMaintainId.value,
        technicalAdviserId: data.technicalAdviserId,
        technicalAdviser: data.technicalAdviser,
        technicalAdviserPhone: data.contactPhone
      };
      await allotTechnicalAdviser(params);
      proxy?.$modal.msgSuccess('分配技术顾问成功');
    } else {
      // 批量操作
      const promises = ids.value.map((id) => {
        const params: AllotTechnicalAdviserForm = {
          id: id,
          technicalAdviserId: data.technicalAdviserId,
          technicalAdviser: data.technicalAdviser,
          technicalAdviserPhone: data.contactPhone
        };
        return allotTechnicalAdviser(params);
      });
      await Promise.all(promises);
      proxy?.$modal.msgSuccess('批量分配技术顾问成功');
    }
    await getList();
  } catch (error) {
    console.error('分配技术顾问失败:', error);
    proxy?.$modal.msgError('分配技术顾问失败');
  }
};

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