<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="annualInspectionSn">
              <el-input v-model="queryParams.annualInspectionSn" placeholder="请输入年检编号" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="年检名称" prop="annualInspectionName">
              <el-input v-model="queryParams.annualInspectionName" placeholder="请输入年检名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="queryParams.contact" placeholder="请输入电话" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="年检状态" prop="annualInspectionStatus">
              <el-select v-model="queryParams.annualInspectionStatus" placeholder="请选择年检状态" clearable>
                <el-option v-for="dict in annual_inspection_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="审核时间" style="width: 308px">
              <el-date-picker v-model="dateRangeAuditTime"
                              format="YYYY-MM-DD"
                              value-format="YYYY-MM-DD"
                              type="daterange"
                              range-separator="-"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" />
            </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 v-hasPermi="['annualInspection:annualInspectionAudit:add']" type="primary" plain icon="Plus" @click="handleAdd"-->
          <!--              >新增</el-button-->
          <!--            >-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              v-hasPermi="['annualInspection:annualInspectionAudit:edit']"-->
          <!--              type="success"-->
          <!--              plain-->
          <!--              icon="Edit"-->
          <!--              :disabled="single"-->
          <!--              @click="handleUpdate()"-->
          <!--              >修改</el-button-->
          <!--            >-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <el-button v-hasPermi="['annualInspection:annualInspectionAudit:remove']" type="success" plain
              :disabled="multiple" @click="updateAnnualInspectionStatus()">批量年检</el-button>
            <span style="color: red; font-size: 13px; margin-left: 5px;">
            同时满足信用分90以上、年龄65以下专家自动通过年检
          </span>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button v-hasPermi="['annualInspection:annualInspectionAudit:export']" type="warning" plain icon="Download" @click="handleExport"-->
          <!--              >导出</el-button-->
          <!--            >-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="annualInspectionAuditList" @selection-change="handleSelectionChange">
        <el-table-column :selectable="(row) => row.annualInspectionStatus == '1'" type="selection" width="55"
          align="center" />
        <el-table-column type="index" label="序号" width="80" align="center">
          <template #default="scope">
            <span>{{
              (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="年检编号" align="center" prop="annualInspectionSn" />
        <el-table-column label="年检名称" align="center" prop="annualInspectionName">
          <template #default="scope">
            <span @click="jumpToInspection(scope.row)" style="color: #36d;cursor: pointer;">{{ scope.row.annualInspectionName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="专家名称" align="center" prop="expertName" />
        <el-table-column label="电话" align="center" prop="contact" />
        <el-table-column label="身份证号" align="center" prop="idCard" />
        <el-table-column label="工作单位" align="center" prop="workUnit" />
        <el-table-column label="审核方式" align="center" prop="annualInspectionType">
          <template #default="scope">
            <dict-tag :options="annual_inspection_type" :value="scope.row.annualInspectionType" />
          </template>
        </el-table-column>
        <el-table-column label="年检状态" align="center" prop="annualInspectionStatus">
          <template #default="scope">
            <dict-tag :options="annual_inspection_status" :value="scope.row.annualInspectionStatus" />
          </template>
        </el-table-column>
        <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <span @click="jumpToInspection(scope.row)" style="color: #409EFF;cursor: pointer;">年检</span>
            <el-divider direction="vertical"></el-divider>
            <span @click="handleDelete(scope.row)" style="color: #409EFF;cursor: pointer">删除</span>
            <el-divider direction="vertical" />
            <span @click="handleVerify(scope.row)" style="color: #67C23A; cursor: pointer;">校验</span>

            <!-- <el-tooltip content="年检" placement="top">
              <el-button v-hasPermi="['annualInspection:annualInspectionAudit:edit']" link type="primary" icon="Edit"
                @click="jumpToInspection(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['annualInspection:annualInspectionAudit:remove']" link type="primary"
                icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改年检管理对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="annualInspectionAuditFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="id" prop="id">
          <el-input v-model="form.id" placeholder="请输入id" />
        </el-form-item>
        <el-form-item label="用户 id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户 id" />
        </el-form-item>
        <el-form-item label="专家 id" prop="expertId">
          <el-input v-model="form.expertId" placeholder="请输入专家 id" />
        </el-form-item>
        <el-form-item label="年检编号" prop="annualInspectionSn">
          <el-input v-model="form.annualInspectionSn" placeholder="请输入年检编号" />
        </el-form-item>
        <el-form-item label="年检名称" prop="annualInspectionName">
          <el-input v-model="form.annualInspectionName" placeholder="请输入年检名称" />
        </el-form-item>
        <el-form-item label="审核方式(1 人工年检 2 自动年检)" prop="annualInspectionType">
          <el-select v-model="form.annualInspectionType" placeholder="请选择审核方式(1 人工年检 2 自动年检)">
            <el-option v-for="dict in annual_inspection_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年检状态(1 待年检 2 已通过 3 未通过)" prop="annualInspectionStatus">
          <el-select v-model="form.annualInspectionStatus" placeholder="请选择年检状态(1 待年检 2 已通过 3 未通过)">
            <el-option v-for="dict in annual_inspection_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="审核时间" prop="auditTime">
          <el-date-picker v-model="form.auditTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择审核时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="yearCheck" title="确认年检" width="650px" append-to-body>
      <el-form-item label="审批意见：">
        <el-radio-group @change="changeValue" v-model="opinion">
          <el-radio value="2">通过</el-radio>
          <el-radio value="3">驳回</el-radio>
        </el-radio-group>
        <el-input v-model="opinionTxt" placeholder="此处输入审批意见" />
      </el-form-item>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitDialog">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AnnualInspectionAudit" lang="ts">
import {
  listAnnualInspectionAudit,
  getAnnualInspectionAudit,
  delAnnualInspectionAudit,
  addAnnualInspectionAudit,
  updateAnnualInspectionAudit, batchAnnualInspection
} from '@/api/annualInspection/annualInspectionAudit';
import { verifyHmac } from '@/api/project/maintain';
import { AnnualInspectionAuditVO, AnnualInspectionAuditQuery, AnnualInspectionAuditForm } from '@/api/annualInspection/annualInspectionAudit/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { annual_inspection_type, annual_inspection_status } = toRefs<any>(proxy?.useDict('annual_inspection_type', 'annual_inspection_status'));
const router = useRouter();
const annualInspectionAuditList = ref<AnnualInspectionAuditVO[]>([]);
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 dateRangeAuditTime = ref<[DateModelType, DateModelType]>(['', '']);

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

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

const initFormData: AnnualInspectionAuditForm = {
  id: undefined,
  userId: undefined,
  expertId: undefined,
  annualInspectionSn: undefined,
  annualInspectionName: undefined,
  annualInspectionType: undefined,
  annualInspectionStatus: undefined,
  auditTime: undefined,
};
const data = reactive<PageData<AnnualInspectionAuditForm, AnnualInspectionAuditQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    expertId: undefined,
    contact: undefined,
    annualInspectionSn: undefined,
    annualInspectionName: undefined,
    annualInspectionType: undefined,
    annualInspectionStatus: undefined,
    reason: undefined,
    params: {
      auditTime: undefined
    }
  },
  rules: {
    id: [{ required: true, message: 'id不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户 id不能为空', trigger: 'blur' }],
    expertId: [{ required: true, message: '专家 id不能为空', trigger: 'blur' }],
    annualInspectionSn: [{ required: true, message: '年检编号不能为空', trigger: 'blur' }],
    annualInspectionName: [{ required: true, message: '年检名称不能为空', trigger: 'blur' }],
    annualInspectionType: [{ required: true, message: '审核方式(1 人工年检 2 自动年检)不能为空', trigger: 'change' }],
    annualInspectionStatus: [{ required: true, message: '年检状态(1 待年检 2 已通过 3 未通过)不能为空', trigger: 'change' }],
    auditTime: [{ required: true, message: '审核时间不能为空', trigger: 'blur' }]
  }
});

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

/** 查询年检管理列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeAuditTime.value, 'AuditTime');
  const res = await listAnnualInspectionAudit(queryParams.value);
  annualInspectionAuditList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
const jumpToInspection = (row) => {
  const userId = row.userId;
  const expertId = row.expertId;
  router.push({ path: '/annualInspection/auditDetail', query: { userId, expertId } })
}
const yearCheck = ref(false);
/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  yearCheck.value = false;
};

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加年检管理';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: AnnualInspectionAuditVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getAnnualInspectionAudit(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改年检管理';
};

/** 提交按钮 */
const submitDialog = async () => {

  if (opinion.value == '') {
    ElMessageBox.alert('请选择审批意见！', '提示', {
      confirmButtonText: '确定',
      callback: () => {
        // ElMessage({
        //     type: 'info',
        //     message: ``,
        // })
      },
    })
    return
  } else if (opinion.value == '3' && opinionTxt.value == '') {
    ElMessageBox.alert('请输入审批意见！', '提示', {
      confirmButtonText: '确定',
      callback: () => {

      },
    })
    return
  }

  await proxy?.$modal.confirm('是否要批量年检的数据项？').finally(() => (loading.value = false));
  yearCheck.value = false;
  form.value.ids = ids.value;
  form.value.annualInspectionStatus = opinion.value;
  form.value.reason = opinionTxt.value;
  await batchAnnualInspection(form.value);
  proxy?.$modal.msgSuccess('操作成功');
  await getList();

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

/** 删除按钮操作 */
const handleDelete = async (row?: AnnualInspectionAuditVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否要批量年检"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delAnnualInspectionAudit(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
/**
 * 批量年检
 * @param row
 */
const updateAnnualInspectionStatus = async () => {
  yearCheck.value = true;
  // await proxy?.$modal.confirm('是否要批脸年检的数据项？').finally(() => (loading.value = false));
  // form.value.ids = ids.value;
  // form.value.annualInspectionStatus = '2';
  // await batchAnnualInspection(form.value);
  // proxy?.$modal.msgSuccess('操作成功');
  // await getList();
};
const opinion = ref('');
const opinionTxt = ref('');
//单选框改变
const changeValue = (value) => {
  value == '2' ? opinionTxt.value = '同意' : opinionTxt.value = '';
}

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

/**hmac校验*/
function handleVerify(row: any) {
  verifyHmac({
    bizType: 'ZjkAnnualInspection',
    id: row.id,
    fields: ["expertId","annualInspectionStatus"]
  })
    .then(result => {
      if (result.match) {
        ElMessage.success('校验通过');
      } else {
        ElMessage.error(`校验失败，该信息被篡改`);
      }
    })
    .catch(err => {
      ElMessage.error('接口请求失败: ' + (err.response?.data?.msg || err.message));
    });
}

onActivated(() => {
  getList();
});

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