<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" label-width="100px">
            <el-form-item label="项目编号" prop="projectCode">
              <el-input v-model="queryParams.projectCode" placeholder="请输入项目编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="售后类型" prop="afterSalesType">
              <el-select v-model="queryParams.afterSalesType" placeholder="请选择售后类型" clearable>
                <el-option v-for="dict in after_sales_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="售后问题是否解决" prop="solveStatus">
              <el-select v-model="queryParams.solveStatus" placeholder="请选择售后问题是否解决" clearable>
                <el-option v-for="dict in solve_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="售后状态" prop="afterSalesStatus">
              <el-select v-model="queryParams.afterSalesStatus" placeholder="请选择售后状态" clearable>
                <el-option v-for="dict in after_sales_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="激活标识" prop="activeFlag">
              <el-select v-model="queryParams.activeFlag" placeholder="请选择激活标识" clearable>
                <el-option v-for="dict in active_flag" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </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="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['oa/erp:afterSales:add']">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/erp:afterSales:edit']"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oa/erp:afterSales:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:afterSales:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="afterSalesList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="售后ID" align="center" prop="afterSalesId" v-if="columns[0].visible" />
        <el-table-column label="售后编号" align="center" prop="afterSalesCode" v-if="columns[2].visible" />
        <el-table-column label="售后主题" align="center" prop="afterSalesSubject" v-if="columns[3].visible" />
        <el-table-column label="项目ID" align="center" prop="projectId" v-if="columns[4].visible" />
        <el-table-column label="项目编号" align="center" prop="projectCode" v-if="columns[5].visible" />
        <el-table-column label="项目名称" align="center" prop="projectName" v-if="columns[6].visible" />
        <el-table-column label="客户ID" align="center" prop="customerId" v-if="columns[7].visible" />
        <el-table-column label="客户名称" align="center" prop="customerName" v-if="columns[8].visible" />
        <el-table-column label="联系人" align="center" prop="contactPerson" v-if="columns[9].visible" />
        <el-table-column label="联系电话" align="center" prop="contactPhone" v-if="columns[10].visible" />
        <el-table-column label="售后日期" align="center" prop="afterSalesDate" width="180" v-if="columns[11].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.afterSalesDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同ID" align="center" prop="contractId" v-if="columns[12].visible" />
        <el-table-column label="合同号" align="center" prop="contractCode" v-if="columns[13].visible">
          <template #default="scope">
            <!-- 如果有编号显示编号，否则显示 '无编号' -->
            {{ scope.row.contractCode ? scope.row.contractCode : '无编号' }}
          </template>
        </el-table-column>
        <el-table-column label="售后类型" align="center" prop="afterSalesType" v-if="columns[14].visible">
          <template #default="scope">
            <dict-tag :options="after_sales_type" :value="scope.row.afterSalesType" />
          </template>
        </el-table-column>
        <el-table-column label="客户干系人" align="center" prop="stakeholderName" v-if="columns[15].visible" />
        <el-table-column label="处理人" align="center" prop="handlerName" v-if="columns[16].visible" />
        <el-table-column label="问题描述" align="center" prop="problemDescription" v-if="columns[17].visible" />
        <el-table-column label="售后总工时" align="center" prop="totalWorkHours" v-if="columns[18].visible" />
        <el-table-column label="售后总成本" align="center" prop="totalCost" v-if="columns[19].visible" />
        <el-table-column label="售后问题是否解决" align="center" prop="solveStatus" v-if="columns[20].visible">
          <template #default="scope">
            <dict-tag :options="solve_status" :value="scope.row.solveStatus" />
          </template>
        </el-table-column>
        <el-table-column label="完成日期" align="center" prop="completionDate" width="180" v-if="columns[21].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.completionDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="处理结果" align="center" prop="processingResult" v-if="columns[22].visible" />
        <el-table-column label="售后状态" align="center" prop="afterSalesStatus" v-if="columns[23].visible">
          <template #default="scope">
            <dict-tag :options="after_sales_status" :value="scope.row.afterSalesStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" v-if="columns[24].visible">
          <template #default="scope">
            <dict-tag :options="flow_status" :value="scope.row.flowStatus" />
          </template>
        </el-table-column>
        <el-table-column label="激活标识" align="center" prop="activeFlag" v-if="columns[25].visible">
          <template #default="scope">
            <dict-tag :options="active_flag" :value="scope.row.activeFlag" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[26].visible" />
        <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:afterSales:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['oa/erp:afterSales:remove']"></el-button>
            </el-tooltip>
          </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>
    <!-- 审批记录 -->
    <ApprovalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="AfterSales" lang="ts">
import { listAfterSales, getAfterSales, delAfterSales, addAfterSales, updateAfterSales } from '@/api/oa/erp/afterSales';
import { AfterSalesVO, AfterSalesQuery, AfterSalesForm } from '@/api/oa/erp/afterSales/types';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const { after_sales_type, after_sales_status, active_flag, solve_status, flow_status } = toRefs<any>(
  proxy?.useDict('after_sales_type', 'after_sales_status', 'active_flag', 'solve_status', 'flow_status')
);

const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const afterSalesList = ref<AfterSalesVO[]>([]);
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 afterSalesFormRef = ref<ElFormInstance>();

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

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `售后ID`, visible: false },
  { key: 1, label: `租户编号`, visible: false },
  { key: 2, label: `售后编号`, visible: true },
  { key: 3, label: `售后主题`, visible: true },
  { key: 4, label: `项目ID`, visible: false },
  { key: 5, label: `项目编号`, visible: true },
  { key: 6, label: `项目名称`, visible: true },
  { key: 7, label: `客户ID`, visible: false },
  { key: 8, label: `客户名称`, visible: true },
  { key: 9, label: `联系人`, visible: true },
  { key: 10, label: `联系电话`, visible: true },
  { key: 11, label: `售后日期`, visible: true },
  { key: 12, label: `合同ID`, visible: false },
  { key: 13, label: `合同号`, visible: true },
  { key: 14, label: `售后类型`, visible: true },
  { key: 15, label: `客户干系人ID`, visible: true },
  { key: 16, label: `处理人ID`, visible: true },
  { key: 17, label: `问题描述`, visible: true },
  { key: 18, label: `售后总工时`, visible: true },
  { key: 19, label: `售后总成本`, visible: true },
  { key: 20, label: `售后问题是否解决`, visible: true },
  { key: 21, label: `完成日期`, visible: true },
  { key: 22, label: `处理结果`, visible: true },
  { key: 23, label: `售后状态`, visible: true },
  { key: 24, label: `流程状态`, visible: true },
  { key: 25, label: `激活标识`, visible: true },
  { key: 26, label: `备注`, visible: true },
  { key: 27, label: `删除标志`, visible: false },
  { key: 28, label: `创建部门`, visible: true },
  { key: 29, label: `创建者`, visible: true },
  { key: 30, label: `创建时间`, visible: true },
  { key: 31, label: `更新者`, visible: true },
  { key: 32, label: `更新时间`, visible: true }
]);

const initFormData: AfterSalesForm = {
  afterSalesId: undefined,
  afterSalesCode: undefined,
  afterSalesSubject: undefined,
  projectId: undefined,
  projectCode: undefined,
  projectName: undefined,
  customerId: undefined,
  customerName: undefined,
  contactPerson: undefined,
  contactPhone: undefined,
  afterSalesDate: undefined,
  contractId: undefined,
  contractCode: undefined,
  afterSalesType: undefined,
  stakeholderId: undefined,
  handlerId: undefined,
  problemDescription: undefined,
  totalWorkHours: undefined,
  totalCost: undefined,
  solveStatus: undefined,
  completionDate: undefined,
  processingResult: undefined,
  afterSalesStatus: undefined,
  flowStatus: undefined,
  activeFlag: undefined,
  remark: undefined
};
const data = reactive<PageData<AfterSalesForm, AfterSalesQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    afterSalesCode: undefined,
    afterSalesSubject: undefined,
    projectId: undefined,
    projectCode: undefined,
    projectName: undefined,
    customerId: undefined,
    customerName: undefined,
    contactPerson: undefined,
    contactPhone: undefined,
    afterSalesDate: undefined,
    contractId: undefined,
    contractCode: undefined,
    afterSalesType: undefined,
    stakeholderId: undefined,
    handlerId: undefined,
    problemDescription: undefined,
    totalWorkHours: undefined,
    totalCost: undefined,
    solveStatus: undefined,
    completionDate: undefined,
    processingResult: undefined,
    afterSalesStatus: undefined,
    flowStatus: undefined,
    activeFlag: undefined,
    params: {}
  },
  rules: {}
});

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

/** 查询项目售后信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAfterSales(queryParams.value);
  afterSalesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  proxy.$tab.closePage(route);
  router.push({
    path: '/project/afterSales/edit',
    query: { type: 'add' }
  });
};

/** 修改按钮操作 */
const handleUpdate = (row?: AfterSalesVO) => {
  const _afterSalesId = row?.afterSalesId || ids.value[0];
  proxy.$tab.closePage(route);
  router.push({
    path: '/project/afterSales/edit',
    query: {
      id: _afterSalesId,
      type: 'update'
    }
  });
};

/** 查看按钮操作 */
const handleView = (row?: AfterSalesVO) => {
  const _afterSalesId = row?.afterSalesId;
  proxy.$tab.closePage(route);
  router.push({
    path: '/erp/afterSales/edit',
    query: {
      id: _afterSalesId,
      type: 'view'
    }
  });
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: AfterSalesVO) => {
  const _afterSalesIds = row?.afterSalesId || ids.value;
  await proxy?.$modal.confirm('是否确认删除项目售后信息编号为"' + _afterSalesIds + '"的数据项？').finally(() => (loading.value = false));
  await delAfterSales(_afterSalesIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

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