<template>
  <div class="p-2 factory-visit-page">
    <!-- 搜索区域 -->
    <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="auto">
            <el-form-item label="访厂ID" prop="visitCode">
              <el-input
                v-model="queryParams.visitCode"
                placeholder="请输入访厂ID"
                clearable
                style="width: 180px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="公司名称" prop="companyName">
              <el-input
                v-model="queryParams.companyName"
                placeholder="请输入公司名称"
                clearable
                style="width: 180px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 160px">
                <el-option
                  v-for="dict in visit_status_dict"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="审核结论" prop="auditResult">
              <el-select
                v-model="queryParams.auditResult"
                placeholder="全部"
                clearable
                style="width: 160px"
              >
                <el-option
                  v-for="dict in visit_audit_result_dict"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="访厂日期" prop="dateRange">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 240px"
              />
            </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="hover">
      <template #header>
        <el-row :gutter="10" class="mb-2">
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['risk:factoryVisit:add']"
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              >新增访厂任务</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['risk:factoryVisit:export']"
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" :data="visitList" border>
        <el-table-column label="访厂ID" align="center" prop="visitCode" width="150" />
        <el-table-column
          label="公司名称"
          align="center"
          prop="companyName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="地址"
          align="center"
          prop="companyAddress"
          width="180"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="访厂日期" align="center" prop="visitDate" width="120">
          <template #default="scope">
            <span>{{ parseDate(scope.row.visitDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="访查实际得分" align="center" prop="totalScore" width="120">
          <template #default="scope">
            <span v-if="scope.row.totalScore != null">{{ scope.row.totalScore }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="审核结论" align="center" prop="auditResult" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.auditResult" :type="getAuditResultTag(scope.row.auditResult)">{{
              scope.row.auditResult
            }}</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="访查人" align="center" prop="visitorName" width="100" />
        <el-table-column
          label="审核产品范围"
          align="center"
          prop="productScope"
          width="160"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="审核部门" align="center" prop="auditDept" width="120" />
        <el-table-column label="评审人" align="center" prop="reviewerName" width="100" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          width="240"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              v-hasPermi="['risk:factoryVisit:list']"
              link
              type="primary"
              icon="Document"
              @click="handleView(scope.row)"
              >查看详情</el-button
            >
            <el-button
              v-if="scope.row.status === '待访厂'"
              v-hasPermi="['risk:factoryVisit:report']"
              link
              type="primary"
              icon="EditPen"
              @click="handleFillReport(scope.row)"
              >填写报告</el-button
            >
            <el-button
              v-if="scope.row.status === '待审核'"
              v-hasPermi="['risk:factoryVisit:audit']"
              link
              type="primary"
              icon="CircleCheck"
              @click="handleAudit(scope.row)"
              >审核</el-button
            >
            <el-button
              v-if="scope.row.status === '待访厂'"
              v-hasPermi="['risk:factoryVisit:edit']"
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-if="scope.row.status === '待访厂'"
              v-hasPermi="['risk:factoryVisit:remove']"
              link
              type="danger"
              icon="Delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </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="780px"
      append-to-body
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="companyName">
              <el-input v-model="form.companyName" placeholder="请输入被访厂商名称" maxlength="200" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核部门" prop="auditDept">
              <el-input v-model="form.auditDept" placeholder="请输入审核部门" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="厂商地址" prop="companyAddress">
              <el-input
                v-model="form.companyAddress"
                placeholder="请输入厂商地址"
                maxlength="500"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="访厂日期" prop="visitDate">
              <el-date-picker
                v-model="form.visitDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择访厂日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="访查人" prop="visitorName">
              <el-input
                v-model="form.visitorName"
                placeholder="请输入访查人"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="评审人" prop="reviewerName">
              <el-input
                v-model="form.reviewerName"
                placeholder="请输入评审人"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核产品范围" prop="productScope">
              <el-input
                v-model="form.productScope"
                placeholder="如:烘焙类、冷链食品等"
                maxlength="200"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
            maxlength="1000"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialog.visible" title="访厂详情" width="900px" append-to-body>
      <el-descriptions v-if="viewDialog.data" :column="2" border>
        <el-descriptions-item label="访厂ID">{{
          viewDialog.data.visitCode
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTag(viewDialog.data.status)">{{ viewDialog.data.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="公司名称">{{
          viewDialog.data.companyName
        }}</el-descriptions-item>
        <el-descriptions-item label="审核部门">{{
          viewDialog.data.auditDept || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{
          viewDialog.data.companyAddress || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="访厂日期">{{
          parseDate(viewDialog.data.visitDate)
        }}</el-descriptions-item>
        <el-descriptions-item label="访查人">{{
          viewDialog.data.visitorName || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="评审人">{{
          viewDialog.data.reviewerName || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="审核产品范围">{{
          viewDialog.data.productScope || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="访查实际得分">{{
          viewDialog.data.totalScore ?? '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="审核结论">
          <el-tag
            v-if="viewDialog.data.auditResult"
            :type="getAuditResultTag(viewDialog.data.auditResult)"
            >{{ viewDialog.data.auditResult }}</el-tag
          >
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="审核人">{{
          viewDialog.data.auditorName || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{
          parseDateTime(viewDialog.data.auditTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="审核意见" :span="2">{{
          viewDialog.data.auditRemark || '-'
        }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{
          viewDialog.data.remark || '-'
        }}</el-descriptions-item>
      </el-descriptions>

      <!-- 报告子表(已审核时也可查看) -->
      <div v-if="viewDialog.data?.report" class="mt-4">
        <el-divider content-position="left">访厂报告</el-divider>
        <el-tabs v-model="activeReportTab" type="border-card">
          <el-tab-pane label="基础信息" name="basic">
            <pre class="report-json">{{
              formatJson(viewDialog.data.report.basicEvaluate)
            }}</pre>
          </el-tab-pane>
          <el-tab-pane label="ESG 评分" name="esg">
            <pre class="report-json">{{ formatJson(viewDialog.data.report.esgScore) }}</pre>
          </el-tab-pane>
          <el-tab-pane label="GMP 评分" name="gmp">
            <pre class="report-json">{{ formatJson(viewDialog.data.report.gmpScore) }}</pre>
          </el-tab-pane>
          <el-tab-pane label="ISO14001" name="iso14001">
            <pre class="report-json">{{
              formatJson(viewDialog.data.report.iso14001Score)
            }}</pre>
          </el-tab-pane>
          <el-tab-pane label="ISO45001" name="iso45001">
            <pre class="report-json">{{
              formatJson(viewDialog.data.report.iso45001Score)
            }}</pre>
          </el-tab-pane>
          <el-tab-pane label="ISO9001" name="iso9001">
            <pre class="report-json">{{
              formatJson(viewDialog.data.report.iso9001Score)
            }}</pre>
          </el-tab-pane>
          <el-tab-pane label="致敏原管控" name="allergen">
            <pre class="report-json">{{
              formatJson(viewDialog.data.report.allergenEvaluate)
            }}</pre>
          </el-tab-pane>
          <el-tab-pane label="问题汇总" name="summary">
            <div class="report-summary">{{ viewDialog.data.report.summary || '(空)' }}</div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <template #footer>
        <el-button @click="viewDialog.visible = false">关 闭</el-button>
      </template>
    </el-dialog>

    <!-- 填写报告弹框 -->
    <ReportDialog
      v-if="reportDialog.visible"
      v-model:visible="reportDialog.visible"
      :visit="reportDialog.data"
      @success="onReportSuccess"
    />

    <!-- 审核弹框 -->
    <el-dialog
      v-model="auditDialog.visible"
      title="审核访厂任务"
      width="560px"
      append-to-body
      @close="closeAuditDialog"
    >
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="访厂ID">
          <span>{{ auditDialog.data?.visitCode }}</span>
        </el-form-item>
        <el-form-item label="公司名称">
          <span>{{ auditDialog.data?.companyName }}</span>
        </el-form-item>
        <el-form-item label="状态">
          <el-tag :type="getStatusTag(auditDialog.data?.status)">{{
            auditDialog.data?.status
          }}</el-tag>
        </el-form-item>
        <el-form-item label="访查得分">
          <span>{{ auditDialog.data?.totalScore ?? '-' }}</span>
        </el-form-item>
        <el-form-item label="审核结论" prop="auditResult">
          <el-select
            v-model="auditForm.auditResult"
            placeholder="请选择审核结论"
            style="width: 100%"
          >
            <el-option
              v-for="dict in visit_audit_result_dict"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核意见" prop="auditRemark">
          <el-input
            v-model="auditForm.auditRemark"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
            maxlength="1000"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditDialog.visible = false">取 消</el-button>
        <el-button type="primary" :loading="auditLoading" @click="submitAudit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="FactoryVisit">
import { ref, reactive, computed, getCurrentInstance, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  listFactoryVisit,
  getFactoryVisit,
  addFactoryVisit,
  updateFactoryVisit,
  delFactoryVisit,
  exportFactoryVisit,
  auditFactoryVisit
} from '@/api/risk/factoryVisit';
import ReportDialog from './components/ReportDialog.vue';

const { proxy } = getCurrentInstance() as any;

// 字典
const { visit_status_dict, visit_audit_result_dict } = proxy.useDict(
  'visit_status',
  'visit_audit_result'
);

const visitList = ref<any[]>([]);
const loading = ref(false);
const submitLoading = ref(false);
const auditLoading = ref(false);
const total = ref(0);
const showSearch = ref(true);
const dateRange = ref<[string, string] | null>(null);
const activeReportTab = ref('basic');

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  visitCode: undefined,
  companyName: undefined,
  status: undefined,
  auditResult: undefined,
  params: {}
});

const initialForm = {
  id: undefined,
  visitCode: undefined,
  companyName: undefined,
  companyAddress: undefined,
  visitDate: undefined,
  visitorName: undefined,
  auditDept: undefined,
  productScope: undefined,
  reviewerName: undefined,
  remark: undefined
};
const form = reactive({ ...initialForm });
const rules = {
  companyName: [{ required: true, message: '公司名称不能为空', trigger: 'blur' }]
};

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

const viewDialog = reactive({
  visible: false,
  data: null as any
});

const reportDialog = reactive({
  visible: false,
  data: null as any
});

const auditDialog = reactive({
  visible: false,
  data: null as any
});

const initialAuditForm = {
  id: undefined,
  auditResult: undefined,
  auditRemark: undefined
};
const auditForm = reactive({ ...initialAuditForm });
const auditRules = {
  auditResult: [{ required: true, message: '请选择审核结论', trigger: 'change' }],
  auditRemark: [{ required: true, message: '请填写审核意见', trigger: 'blur' }]
};

watch(dateRange, (val) => {
  if (val && val.length === 2) {
    queryParams.params = { ...(queryParams.params || {}), beginVisitDate: val[0], endVisitDate: val[1] };
  } else {
    queryParams.params = { ...(queryParams.params || {}) };
    delete (queryParams.params as any).beginVisitDate;
    delete (queryParams.params as any).endVisitDate;
  }
});

// ============ 列表 ============

const getList = async () => {
  loading.value = true;
  try {
    const res: any = await listFactoryVisit(queryParams);
    visitList.value = res.rows || [];
    total.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    visitCode: undefined,
    companyName: undefined,
    status: undefined,
    auditResult: undefined,
    params: {}
  });
  dateRange.value = null;
  getList();
};

// ============ 新增/编辑 ============

const handleAdd = () => {
  Object.assign(form, initialForm);
  dialog.title = '新增访厂任务';
  dialog.visible = true;
};

const handleUpdate = async (row: any) => {
  Object.assign(form, initialForm);
  const res: any = await getFactoryVisit(row.id);
  Object.assign(form, res.data || res);
  dialog.title = '编辑访厂任务';
  dialog.visible = true;
};

const submitForm = async () => {
  const formRef = proxy.$refs.formRef;
  await formRef.validate();
  submitLoading.value = true;
  try {
    if (form.id) {
      await updateFactoryVisit(form);
      ElMessage.success('修改成功');
    } else {
      await addFactoryVisit(form);
      ElMessage.success('新增成功');
    }
    dialog.visible = false;
    getList();
  } finally {
    submitLoading.value = false;
  }
};

const cancel = () => {
  dialog.visible = false;
  Object.assign(form, initialForm);
};

const closeDialog = () => {
  Object.assign(form, initialForm);
};

const handleDelete = async (row: any) => {
  await ElMessageBox.confirm(`确认删除访厂任务 "${row.visitCode}" ?`, '提示', {
    type: 'warning'
  });
  await delFactoryVisit(row.id);
  ElMessage.success('删除成功');
  getList();
};

// ============ 查看详情 ============

const handleView = async (row: any) => {
  const res: any = await getFactoryVisit(row.id);
  viewDialog.data = res.data || res;
  viewDialog.visible = true;
};

// ============ 填写报告 ============

const handleFillReport = async (row: any) => {
  const res: any = await getFactoryVisit(row.id);
  reportDialog.data = res.data || res;
  reportDialog.visible = true;
};

const onReportSuccess = () => {
  reportDialog.visible = false;
  getList();
};

// ============ 审核 ============

const handleAudit = (row: any) => {
  Object.assign(auditForm, initialAuditForm);
  auditDialog.data = row;
  auditDialog.visible = true;
};

const submitAudit = async () => {
  const ref: any = proxy.$refs.auditFormRef;
  await ref.validate();
  auditLoading.value = true;
  try {
    await auditFactoryVisit({
      id: auditDialog.data.id,
      auditResult: auditForm.auditResult,
      auditRemark: auditForm.auditRemark
    });
    ElMessage.success('审核成功');
    auditDialog.visible = false;
    getList();
  } finally {
    auditLoading.value = false;
  }
};

const closeAuditDialog = () => {
  Object.assign(auditForm, initialAuditForm);
};

// ============ 导出 ============

const handleExport = async () => {
  const res: any = await exportFactoryVisit(queryParams);
  proxy.download(res);
};

// ============ 辅助 ============

const getAuditResultTag = (result?: string): 'success' | 'danger' | 'info' => {
  if (result === '通过') return 'success';
  if (result === '不通过') return 'danger';
  if (result === '待定') return 'info';
  return 'info';
};

const getStatusTag = (status?: string): 'warning' | 'primary' | 'success' | 'info' => {
  if (status === '待访厂') return 'warning';
  if (status === '待审核') return 'primary';
  if (status === '已审核') return 'success';
  return 'info';
};

const parseDate = (d?: string | Date) => {
  if (!d) return '-';
  const s = typeof d === 'string' ? d : d.toISOString();
  return s.substring(0, 10);
};

const parseDateTime = (d?: string | Date) => {
  if (!d) return '-';
  const s = typeof d === 'string' ? d : d.toISOString();
  return s.substring(0, 19).replace('T', ' ');
};

const formatJson = (data: any) => {
  if (!data) return '(空)';
  try {
    return JSON.stringify(data, null, 2);
  } catch {
    return String(data);
  }
};

getList();
</script>

<style scoped lang="scss">
.factory-visit-page {
  .report-json {
    background: #f5f7fa;
    padding: 12px;
    border-radius: 4px;
    font-size: 13px;
    line-height: 1.6;
    max-height: 400px;
    overflow: auto;
    white-space: pre-wrap;
    word-break: break-all;
  }
  .report-summary {
    background: #f5f7fa;
    padding: 16px;
    border-radius: 4px;
    line-height: 1.8;
    min-height: 100px;
    white-space: pre-wrap;
  }
}
</style>