<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerModal"
    destroyOnClose
    :centered="true"
    :width="windowWidth"
    :useWrapper="true"
    :footer="null"
    @cancel="handleCancel"
    :defaultFullscreen="true"
  >
    <div style="background-color: #ececec; padding: 5px; overflow-y: auto">
      <a-row :gutter="8">
        <a-col :span="24 - areaColSpanCenter">
          <div :style="{ overflow: 'hidden', height: '87vh' }">
            <template v-if="isUpdate && curCheckPoint.citemid">
              <a-card
                size="small"
                :bordered="false"
                contentFullHeight="true"
                :loading="loading"
                style="height: 100%; overflow-y: hidden"
                :bodyStyle="{ height: '100%', padding: '10px 0px', margin: '0px 10px' }"
              >
                <template #title>
                  <p style="font-size: 14px">合规条目</p>
                </template>
                <template #extra>
                  <a-button type="link" :disabled="prevDisabled" @click="handlePrevious()">上一条</a-button>
                  <a-button type="link" :disabled="nextDisabled" @click="handleNext()">下一条</a-button>
                  <a-button type="link" @click="gotoComplianeItem()">查看全部</a-button>
                </template>

                <div style="height: 92%">
                  <div style="height: 30%; margin-bottom: 10px">
                    <vxe-table auto-resize height="auto" :show-header="false" :data="detailData">
                      <vxe-column field="label" width="20%" />
                      <vxe-column field="value" />
                    </vxe-table>
                  </div>
                  <vxe-table
                    ref="tableRef"
                    size="small"
                    border
                    height="auto"
                    :show-radio="true"
                    style="height: 100%; overflow-y: scroll"
                    :row-config="{ isCurrent: true, isHover: true }"
                    @current-change="currentChangeEvent"
                    :column-config="{ resizable: true }"
                    :radio-config="{ highlight: true }"
                    auto-resize
                    :data="checkMethods"
                  >
                    <vxe-column type="radio" width="50" />
                    <vxe-column field="content" width="70%" title="检查点" />
                    <vxe-column field="des" title="说明" />
                  </vxe-table>
                </div>
              </a-card>
            </template>
            <template v-else>
              <a-card
                size="small"
                :bordered="false"
                contentFullHeight="true"
                :loading="loading"
                style="height: 100%; overflow-y: hidden"
                :bodyStyle="{ height: '100%', padding: '5px 0px', margin: '0px 1px' }"
              >
                <template #title
                  ><span>{{ title }}</span></template
                >
                <template #extra>
                  <a-button type="link" @click="saveCheckMethod()">保存</a-button>
                  <a-button type="link" @click="refresh()"> 刷新</a-button>
                </template>
                <AuditCheckMethodForm ref="refAuditCheckMethodForm" @callback="setNewCheckMethod" />
              </a-card>
            </template>
          </div>
        </a-col>
        <a-col :span="areaColSpanCenter">
          <div :style="{ overflow: 'hidden', height: '87vh', background: '#fff' }">
            <a-card
              size="small"
              :bordered="false"
              contentFullHeight="true"
              :loading="loading"
              style="height: 100%; overflow-y: hidden"
              :bodyStyle="{ height: '100%', padding: '5px 0px', margin: '0px 1px' }"
            >
              <template #title><span>编辑检查方法</span></template>
              <template #extra>
                <a-button type="link" @click="insertEvent(null)">添加</a-button>
                <a-button type="link" @click="refresh()"> 刷新</a-button>
              </template>

              <vxe-table
                keep-source
                ref="tablecCheckItemRef"
                size="small"
                height="100%"
                :data="dataCheckItemList"
                :show-radio="true"
                :row-config="{ isCurrent: true, isHover: true, useKey: true, resizable: true }"
                :column-config="{ resizable: true, useKey: true }"
                :scroll-y="{ enabled: true, gt: 60 }"
                :edit-config="{ trigger: 'manual', mode: 'row' }"
                :radio-config="{ labelField: 'name', highlight: true }"
              >
                <template #empty>
                  <vxe-button mode="text" icon="vxe-icon-add" @click="insertEvent(null)">
                    <div style="font-size: 20px"> 添加</div>
                  </vxe-button>
                </template>

                <vxe-column type="seq" width="50" row-resize />
                <vxe-column field="id" :visible="false" />
                <vxe-column field="checkid" :visible="false" />
                <vxe-column field="checkid" type="html" title="" :visible="false" />
                <vxe-column
                  field="tp"
                  title="类别"
                  width="20%"
                  :edit-render="{ autofocus: '.my-input', autoselect: true }"
                  :sortable="true"
                  :filters="tpOptions"
                >
                  <template #default="{ row }">
                    {{ setRowTpName(row) }}
                  </template>
                  <template #edit="{ row }">
                    <vxe-radio-group v-model="row.tp" style="min-height: 60px; overflow-y: hidden">
                      <vxe-radio style="margin: 5px" v-for="item in tpOptions" :key="item.value" :label="item.value * 1" :content="item.label" />
                    </vxe-radio-group>
                  </template>
                </vxe-column>

                <vxe-column field="method" title="检查方法" :edit-render="{ autofocus: '.my-input', autoselect: true }" :sortable="true">
                  <template #default="{ row }">
                    <span v-html="row.method"></span>
                  </template>
                  <template #edit="{ row }">
                    <vxe-textarea
                      v-model="row.method"
                      style="min-height: 60px"
                      type="text"
                      placeholder="请输入检查方法"
                      size="small"
                      clearable
                      :rows="2"
                    />
                  </template>
                </vxe-column>

                <vxe-column field="name" title="监管要求" width="25%" v-if="curCheckPoint.citemid">
                  <template #default="{ row }">
                    {{ row.name }}
                  </template>
                </vxe-column>

                <vxe-column field="des" title="监管要求说明" width="15%" v-if="curCheckPoint.citemid">
                  <template #default="{ row }">
                    {{ row.des }}
                  </template>
                </vxe-column>

                <vxe-column field="id" title="" :visible="false" />

                <vxe-column title="操作" width="100">
                  <template #default="{ row }">
                    <template v-if="hasActiveEditRow(row)">
                      <vxe-button mode="text" size="small" content="取消" @click="clearRowEvent(row)" />
                      <vxe-button mode="text" size="small" status="primary" content="保存" @click="saveRowEvent(row)" />
                    </template>
                    <template v-else>
                      <vxe-button mode="text" size="small" content="编辑" @click="editRowEvent(row)" />
                      <vxe-button mode="text" @click="removeEvent(row)">删除 </vxe-button>
                    </template>
                  </template>
                </vxe-column>
              </vxe-table>
            </a-card>
          </div>
        </a-col>
      </a-row>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';

  import { getDictItemsByCode } from '/@/utils/dict/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { saveOrUpdate, queryByCheckId, deleteOne } from '../api/AuditCheckMethodItem.api';

  import { queryItemCheckMethodByItemId } from '../api/AuditComplianeItem.api';
  import { VxeUI } from 'vxe-table';
  import AuditCheckMethodForm from './AuditCheckMethodForm.vue';

  const emit = defineEmits(['register', 'success', 'callback']);

  const isUpdate = ref(true);
  const isDetail = ref(false);
  const loading = ref(false);
  const windowWidth = ref('100%');
  const areaColSpanCenter = ref(14);
  const checkMethods = ref([]);
  const tableRef = ref();
  const tablecCheckItemRef = ref();

  const allData = ref();
  const tpOptions = ref();

  const curRowInd = ref(-1);
  const prevDisabled = ref(false);
  const nextDisabled = ref(false);
  const curCheckPoint = ref({});
  const dataCheckItemList = ref([]);
  const docFile = ref({});

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    tpOptions.value = await getDictItemsByCode('check_item_tp');
    isUpdate.value = data.isUpdate;
    docFile.value = data.docFile;
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });

    curCheckPoint.value = data.record;
    allData.value = Array.from(
      new Set(
        data.allData.map(({ citemid, item, itemContent, cgrpPath, fileName }) => JSON.stringify({ citemid, item, itemContent, cgrpPath, fileName }))
      )
    ).map((data) => JSON.parse(data));

    if (isUpdate.value) {
      if (data.record?.citemid) {
        curRowInd.value = await allData.value.findIndex((item) => item.citemid == data.record?.citemid);
        await setCheckMethodByCheckId();
        await setComplianeItem(data.record);
        await setCheckMethods();
      } else {
        refAuditCheckMethodForm.value.initFormData(curCheckPoint.value);
        await setCheckMethodByCheckId();
      }
    } else {
    }
  });

  const title = computed(() => (!unref(isUpdate) ? '新增' : unref(isDetail) ? '查看' : '修改'));

  async function setCheckMethodByCheckId() {
    const checkid = curCheckPoint.value?.id;
    if (!checkid) return;
    dataCheckItemList.value = await queryByCheckId({ checkid });
    tablecCheckItemRef.value.loadData(dataCheckItemList.value);
  }

  const detailData = ref([]);

  async function setComplianeItem(data) {
    detailData.value = [
      { label: '条目名称', value: data?.item },
      { label: '条目说明', value: data?.itemContent },
      { label: '参考文件', value: data?.fileName },
    ];
  }

  const currentChangeEvent = async ({ row }) => {
    curCheckPoint.value = row;
    const $table = tableRef.value;
    $table.setRadioRow(row);
    setCheckMethodByCheckId(row.id);
  };

  function gotoComplianeItem() {
    emit('callback', 5, docFile.value);
  }

  async function handlePrevious() {
    dataCheckItemList.value = [];
    curRowInd.value -= 1;
    curCheckPoint.value = allData.value[curRowInd.value];
    await setCheckMethods();
    if (curCheckPoint.value?.citemid) {
      await setComplianeItem(curCheckPoint.value);
    } else {
      await handlePrevious();
    }
  }

  async function handleNext() {
    dataCheckItemList.value = [];
    curRowInd.value += 1;
    curCheckPoint.value = allData.value[curRowInd.value];
    await setCheckMethods();

    if (curCheckPoint.value?.citemid) {
      await setComplianeItem(curCheckPoint.value);
    } else {
      await handleNext();
    }
  }

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

  function handleCancel() {
    closeModal();
    emit('success', isUpdate.value);
  }

  const removeEvent = async (row) => {
    const $table = tablecCheckItemRef.value;
    if (!$table) return;
    const type = await VxeUI.modal.confirm('您确定要删除该数据?');
    if (type === 'confirm') {
      if (row.id) {
        const params = { id: row.id };
        deleteOne(params, null);
        $table.remove(row);
      }
    }
  };
  const insertEvent = async (row) => {
    const $table = tablecCheckItemRef.value;
    if ($table) {
      const record = {
        id: row?.id,
        tp: row?.tp,
        name: row?.name,
        des: row?.des,
      };
      const { row: newRow } = await $table.insertAt(record, row);
      await $table.setEditCell(newRow, 'tp', 'name');
    }
  };

  const hasActiveEditRow = (row) => {
    const $grid = tablecCheckItemRef.value;
    if ($grid) {
      return $grid.isEditByRow(row);
    }
    return false;
  };

  const clearRowEvent = (row) => {
    const $grid = tablecCheckItemRef.value;
    if ($grid) {
      $grid.clearEdit().then(() => {
        $grid.revertData(row);
      });
    }
  };

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

  const saveRowEvent = async (row) => {
    const $grid = tablecCheckItemRef.value;
    if ($grid) {
      try {
        let formData = {};
        if (row.id) {
          formData['id'] = row.id;
        }
        await $grid.clearEdit();
        let checkid = row.checkid || curCheckPoint.value?.id;

        if (!checkid) {
          checkid = await refAuditCheckMethodForm.value.getNewMethodId();
        }
        formData['method'] = row.method;
        formData['tp'] = row.tp;
        formData['methodDes'] = row.methodDes;
        formData['checkid'] = checkid;
        formData['name'] = row.name;
        formData['des'] = row.des;
        await saveOrUpdate(formData, !!row.id);
      } catch (e) {
        console.log(e);
      } finally {
        loading.value = false;
      }
    }
  };

  const refresh = async () => {
    await setCheckMethodByCheckId();
    const $grid = tablecCheckItemRef.value;
    await $grid.clearEdit();
  };

  async function setCheckMethods() {
    const curData = allData.value[curRowInd.value];
    const itemid = curData?.citemid;
    checkMethods.value = await queryItemCheckMethodByItemId({ id: itemid });
    if (!checkMethods.value || checkMethods.value.length == 0) {
      return;
    }

    const checkid = curCheckPoint.value.id;
    const curInd = checkMethods.value.findIndex((item) => item.id == checkid);
    const $table = tableRef.value;

    $table.setCurrentRow(checkMethods.value[curInd]);
    $table.setRadioRow(checkMethods.value[curInd]);

    await setCurCheckMethod(checkMethods.value[curInd]);
  }

  async function setCurCheckMethod(data) {
    // const retData = await queryCheckMethodById(data.id);
    // if (data['actIds'] && data['caName']) {
    //   let actIds = data['actIds'].split(',').map(Number);
    //   let caNams = data['caName'].split(',');
    //   retData['actIds'] = [caNams, actIds];
    // }
  }

  const refAuditCheckMethodForm = ref();
  function saveCheckMethod() {
    refAuditCheckMethodForm.value.submitForm();
  }

  function setNewCheckMethod(data) {
    curCheckPoint.value = data;
  }
</script>

<style lang="less" scoped>
  :deep(.ant-input-number) {
    width: 100%;
  }
  :deep(.ant-calendar-picker) {
    width: 100%;
  }
</style>
