<template>
  <div>
    <a-drawer
      title="内容填报"
      placement="right"
      width="100%"
      :visible="showDrawer"
      @close="closeDrawer"
      :style="{ position: 'absolute', margin: '0' }"
    >
      <template #extra>
        <a-button type="link" size="small" @click="closeDrawer">关闭</a-button>
      </template>
      <div style="background-color: #f5f5f5; padding: 8px; height: 100%">
        <a-row :gutter="8" style="height: 100%">
          <a-col :span="24 - rightWidth">
            <div style="height: 100%; background: #fff; border-radius: 4px; overflow: hidden">
              <a-descriptions
                bordered
                :column="1"
                :labelStyle="{ width: '100px', color: '#1890ff', fontWeight: '500' }"
                layout="vertical"
                style="width: 100%; height: 100%; overflow-y: auto"
              >
                <template #title>
                  <div style="margin-top: 5px">{{ curProject.name }}</div>
                </template>
                <template #extra>
                  <vxe-button style="margin-top: 5px" @click="toggleFullscreen('left')" status="primary" mode="text" icon="vxe-icon-fullscreen" />
                </template>
                <a-descriptions-item label="检查项">
                  <div class="description-content" v-html="curCheckMethod?.content"></div>
                </a-descriptions-item>
                <a-descriptions-item label="合规条目">
                  <div class="description-content" v-html="curCheckMethod?.item"></div>
                </a-descriptions-item>
                <a-descriptions-item label="合规内容">
                  <div class="description-content" style="max-height: 200px">
                    <span v-html="curCheckMethod?.complineContent"></span>
                  </div>
                </a-descriptions-item>
                <a-descriptions-item label="控制项">
                  <template v-if="curCheckMethod?.actNames">
                    <span v-for="item in curCheckMethod.actNames.split(',')" :key="item">
                      <span v-html="item"></span>
                    </span>
                  </template>
                </a-descriptions-item>
                <a-descriptions-item label="参考文件">
                  <a-button type="link" size="small" @click="handleShowFile()">
                    <span v-html="curCheckMethod?.fileName"></span>
                  </a-button>
                </a-descriptions-item>
                <a-descriptions-item label="说明">
                  <span class="description-content" v-html="curCheckMethod?.checkDes"></span>
                </a-descriptions-item>
              </a-descriptions>
            </div>
          </a-col>
          <a-col :span="rightWidth">
            <vxe-grid v-bind="gridOptions" ref="gridRef">
              <template #toolbarButtons>
                <a href="#" style="margin: 10px; font-size: 15px">检查项包含的检查点</a>
              </template>
              <template #tp_default="{ row }">
                {{ setRowTpName(row) }}
              </template>

              <template #situation_default="{ row }">
                {{ row.situation }}
              </template>

              <template #situation_edit="{ row }">
                <vxe-textarea v-model="row.situation" style="height: 100%; width: 100%" :autosize="{ minRows: 3, maxRows: 10 }" clearable />
              </template>

              <template #issues_default="{ row }">
                {{ row.issues }}
              </template>

              <template #issues_edit="{ row }">
                <vxe-textarea v-model="row.issues" style="height: 100%; width: 100%" :autosize="{ minRows: 3, maxRows: 10 }" clearable />
              </template>

              <template #score1_default="{ row }">
                <a-rate v-model:value="row.score" disabled />
              </template>

              <template #score1_edit="{ row }">
                <a-rate v-model:value="row.score" />
              </template>

              <template #action="{ row }">
                <template v-if="hasEditStatus(row)">
                  <vxe-button mode="text" @click="saveRowEvent(row)">保存</vxe-button>
                  <vxe-button mode="text" @click="cancelRowEvent()">取消</vxe-button>
                </template>
                <template v-else>
                  <vxe-button mode="text" @click="editRowEvent(row)">编辑</vxe-button>
                </template>
              </template>
            </vxe-grid>
          </a-col>
        </a-row>
      </div>
    </a-drawer>

    <a-drawer title="文件预览" placement="left" width="50%" :mask="true" :visible="showFileDrawer" @close="closeFileDrawer" :style="{ margin: '0' }">
      <template #extra>
        <a-button type="link" size="small" @click="closeFileDrawer">关闭</a-button>
      </template>
      <FileViewer ref="refShowFile" />
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, nextTick, reactive } from 'vue';
  import { getProjectItems } from '../AuditProjectItem.api';
  import { queryAllReports, saveOrUpdate } from '/@/views/newlib/components/api/AuditTaskReport.api';
  import FileViewer from '/@/components/onlinePreview/FileViewer.vue';

  import { listCriteria, listConfig } from '../../criteria/AuditCriteria.api';

  const dataList = ref<any[]>([]);
  const refShowFile = ref();
  const rightWidth = ref(17);

  const showDrawer = ref(false);
  const tpOptions = ref<any[]>([]);
  const curCheckMethod = ref<any>(null);
  const gridRef = ref();
  const curProject = ref<any>(null);
  const showFileDrawer = ref(false);

  function closeDrawer() {
    showDrawer.value = false;
  }

  function handleShowFile() {
    showFileDrawer.value = true;
    const fileObj = {
      fileName: curCheckMethod.value?.fileName,
      fileId: curCheckMethod.value?.fileId,
      fileTp: curCheckMethod.value?.fileTp,
      filePath: curCheckMethod.value?.filePath,
    };

    nextTick(async () => {
      await refShowFile.value?.setDocFile(fileObj);
    });
  }

  function closeFileDrawer() {
    showFileDrawer.value = false;
  }

  const setRowTpName = (row: any) => {
    const foundOption = tpOptions.value?.find((option) => option.value * 1 === row.tp * 1);
    return foundOption?.label || '';
  };

  const toggleFullscreen = (side: 'left' | 'right') => {
    if (side === 'left') {
      rightWidth.value = rightWidth.value === 0 ? 17 : 0;
    } else {
      rightWidth.value = rightWidth.value === 24 ? 17 : 24;
    }
  };

  const gridOptions = reactive<any>({
    border:true,
    height: 'auto',
    columnConfig: {
      resizable: true,
    },
    columns: [
      { type: 'seq', width: 50 },
      { field: 'tp', title: '分类', slots: { default: 'tp_default' }, width: '100' },
      { field: 'name', title: '检查方法', width: '150' },
      { field: 'situation', title: '当前现状：', editRender: {}, slots: { default: 'situation_default', edit: 'situation_edit' }, width: '150' },
      { field: 'issues', title: '存在问题：', editRender: {}, slots: { default: 'issues_default', edit: 'issues_edit' }, width: '150' },

      { field: 'desc', title: '备注', editRender: { name: 'VxeInput' }, width: '150', visible: false },
      { field: 'reportId', title: 'reportId', visible: false },
      { field: 'id', title: 'id', visible: false },
      { title: '操作', slots: { default: 'action' }, width: '120' },
    ],
    editConfig: {
      trigger: 'dblclick',
      mode: 'row',
    },
    toolbarConfig: {
      refresh: true,
      zoom: true,
      slots: {
        buttons: 'toolbarButtons',
      },
    },
    data: dataList,
  });

  const baseColumns: any[] = gridOptions.columns.slice();

  const hasEditStatus = (row) => {
    const $grid = gridRef.value;
    if ($grid) {
      return $grid.isEditByRow(row);
    }
  };

  const editRowEvent = (row) => {
    const $grid = gridRef.value;
    if ($grid) {
      $grid.setEditRow(row);
    }
  };

  const criterias = ref();

  const saveRowEvent = async (element) => {
    const $grid = gridRef.value;
    if ($grid) {
      $grid.clearEdit().then(async () => {
        gridOptions.loading = true;
        const newData = {
          id: element.reportId,
          checkid: element.checkid,
          checkItemTp: element.tp,
          checkItemId: element.id,
          projectid: curProject.value?.id,
          situation: element.situation,
          issues: element.issues,
          score: element.score,
        };
        const scoreKeyAry: string[] = [];
        criterias.value.forEach((ele: any) => {
          const val = element['col_' + ele.code];
          if (val) {
            scoreKeyAry.push(String(val));
          }
        });
        newData['scoreKey'] = scoreKeyAry.join('-');
        //await batchAddOrUpdate([newData]);
        let isUpdate = newData.id ? true : false;
        await saveOrUpdate(newData, isUpdate);

        setTimeout(() => {
          gridOptions.loading = false;
        }, 300);
      });
    }
  };

  const cancelRowEvent = () => {
    const $grid = gridRef.value;
    if ($grid) {
      $grid.clearEdit();
    }
  };

  const formatLevelLabel = (level) => {
    if (!level) return '未知';
    if (level == 2) return '可接受';
    if (level == 3) return '低风险';
    if ((level = 4)) return '中风险';
    if ((level = 5)) return '高风险';
    return '未知';
  };

  async function iniData(check: any, project: any, tpOpt: any[]) {
    curProject.value = project;
    curCheckMethod.value = check;
    tpOptions.value = tpOpt;
    if (Array.isArray(baseColumns) && baseColumns.length) {
      gridOptions.columns.splice(0, gridOptions.columns.length, ...baseColumns);
    }

    const params = {
      checkid: check.checkid,
      pid: project.id,
    };

    dataList.value = await getProjectItems(params);
    const reprotExists = await queryAllReports(params);
    criterias.value = await listCriteria({});
    const criteriasConfig = await listConfig({});

    dataList.value.forEach((ele) => {
      const report = reprotExists[ele.id];
      if (report) {
        ele.situation = report.situation;
        ele.issues = report.issues;
        ele.score = report.score;
        ele.reportId = report.id;
        ele.scoreKey = report.scoreKey;
        if (report.scoreKey) {
          ele.level = formatLevelLabel(report.level);

          const newScoreObj = scoreKeyParse(report.scoreKey);
          Object.assign(ele, newScoreObj);
        }

        if (project.scoreTp > 1 && report.score < 3) {
          ele.score = 1;
        }
      }
    });

    if (project.scoreTp == 1) {
      let newColumn = {
        field: 'score',
        title: '评分',
        editRender: {},
        slots: { default: 'score1_default', edit: 'score1_edit' },
      };
      gridOptions['columns'].splice(5, 0, newColumn);
    } else if (project.scoreTp == 2) {
      let newColumn = {
        field: 'score',
        title: '评分',
        editRender: {
          name: 'VxeSelect',
          options: [
            { value: 1, label: '可接受' },
            { value: 3, label: '低风险' },
            { value: 4, label: '中风险' },
            { value: 5, label: '高风险' },
          ],
        },
      };
      gridOptions['columns'].splice(5, 0, newColumn);
    } else if (project.scoreTp == 3) {
      const selectOptionsObj = {};
      criteriasConfig.forEach((config) => {
        const criteriaId = config.criteriaId;
        if (!selectOptionsObj[criteriaId]) {
          selectOptionsObj[criteriaId] = [];
        }
        selectOptionsObj[criteriaId].push({
          value: criteriaId + '_' + config.code,
          label: config.name,
        });
      });
      let newColumn: any[] = [];
      criterias.value.forEach((item) => {
        newColumn.push({
          field: 'col_' + item.code,
          title: item.name,
          editRender: {
            name: 'VxeSelect',
            options: selectOptionsObj[item.id],
            props: {
              clearable: true,
              placeholder: '请选择评分',
            },
          },
        });
      });

      const newColumns = {
        title: '多维度评价',
        children: newColumn,
        minWidth:200
      };

      gridOptions['columns'].splice(5, 0, newColumns);
      gridOptions['columns'].splice(6, 0, {
        field: 'score',
        title: '得分',
        width:70
      });
      gridOptions['columns'].splice(7, 0, {
        field: 'level',
        title: '等级',
        width:70
      });
    }
    showDrawer.value = true;
  }

  const scoreKeyParse = (scoreKey) => {
    const result = {};
    scoreKey.split('-').forEach((pair) => {
      const [key] = pair.split('_');
      result['col_' + key] = pair;
    });
    return result;
  };

  defineExpose({
    iniData,
  });
</script>

<style lang="less" scoped>
  .ant-row {
    margin-left: -4px !important;
    margin-right: -4px !important;
  }

  .ant-col {
    padding-left: 4px !important;
    padding-right: 4px !important;
  }

  :deep(.ant-descriptions) {
    .ant-descriptions-item-label {
      width: 100px;
      padding: 6px 8px;
    }

    .ant-descriptions-item-content {
      padding: 6px 8px;
    }
  }

  .description-content {
    max-height: 200px;
    overflow-y: auto;
    word-break: break-word;
  }

  :deep(.ant-card) {
    border-radius: 4px;

    .ant-card-head {
      min-height: 48px;
      padding: 0 8px;

      .ant-card-head-title {
        padding: 8px 0;
        font-size: 14px;
      }

      .ant-card-extra {
        padding: 8px 0;
      }
    }
  }

  :deep(.vxe-table) {
    .vxe-header--column {
      padding: 6px 8px;
      font-weight: 500;
    }

    .vxe-body--column {
      padding: 6px 8px;
      line-height: 1.4;
    }

    .vxe-cell {
      .vxe-input,
      .vxe-textarea {
        padding: 4px 6px;
        min-height: 32px;
      }
    }
  }

  .compact-textarea {
    padding: 4px 6px !important;
    min-height: 32px !important;
    line-height: 1.4 !important;
  }

  .ant-btn {
    + .ant-btn {
      margin-left: 6px;
    }
  }
</style>
