<template>
  <div style="background-color: #ececec; padding: 10px;height: 88vh;">
    <a-row :gutter="[8,8]"  style="height: 80vh;">
      <a-col :span="leftWidth" style="">
        <a-card title="评估模型" :bordered="false" style="height:100%;" :bodyStyle="{height:'80vh',overflow:'auto'}"  :loading="loading[0]">
          <vxe-grid v-bind="criteriaGridOptions" ref="gridRef">
            <template #toolbarButtons>
              <vxe-button status="primary" icon="vxe-icon-add" @click="handleAdd">新增</vxe-button>
            </template>
            <template #toolsButtons>
              <a-space>
                <vxe-button status="primary" @click="setCriteriaList">刷新</vxe-button>
              </a-space>
            </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>
                <vxe-button  mode="text" icon="vxe-icon-delete" @click="handleCriteraDelete(row)"></vxe-button>
                <vxe-button mode="text" @click="setConfigList(row)" icon="vxe-icon-arrow-right"></vxe-button>
              </template>
            </template>
          </vxe-grid>
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card title="模型条目" :bordered="false"  style="height:100%" :loading="loading[1]" :bodyStyle="{height:'80vh',overflow:'auto'}">
          <vxe-grid v-bind="configGridOptions" ref="gridConfigRef">
            <template #toolbarButtons>
              <vxe-button status="primary" icon="vxe-icon-add" @click="handleAddConfig">新增</vxe-button>
            </template>
            <template #toolsButtons>
              <a-space>
                <vxe-button status="primary" @click="setConfigList">刷新</vxe-button>
              </a-space>
            </template>
            <template #action="{ row }">
              <template v-if="hasConfigEditStatus(row)">
                <vxe-button mode="text" @click="saveConfigRowEvent(row)">保存</vxe-button>
                <vxe-button mode="text" @click="cancelConfigRowEvent()">取消</vxe-button>
              </template>
              <template v-else>
                <vxe-button mode="text" @click="editConfigRowEvent(row)" v-show="curSelectCriteria.code">编辑</vxe-button>
                <vxe-button mode="text" icon="vxe-icon-delete" @click="handleConfigDelete(row)" v-show="curSelectCriteria.code"></vxe-button>
                <vxe-button mode="text" @click="setScoreList(row)" icon="vxe-icon-arrow-right"></vxe-button>
              </template>
            </template>
          </vxe-grid>
        </a-card>
      </a-col>
      <a-col :span="16-leftWidth">
        <a-card title="计算分数"  :bordered="false"  style="height:100%;" :bodyStyle="{height:'80vh',overflow:'auto'}" :loading="loading[2]">
          <vxe-grid v-bind="scoresGridOptions" ref="gridScoresRef">
            <template #toolbarButtons>
              <a-space>
                <!-- <vxe-select v-model="computeFormula" placeholder="选择计算方式" clearable>
                  <vxe-option value="1" label="最大值"></vxe-option>
                  <vxe-option value="2" label="最小值"></vxe-option>
                  <vxe-option value="3" label="计算公式"></vxe-option>
                </vxe-select> -->
                <vxe-button status="primary"  @click="handleComputeData">生成数据</vxe-button>
              </a-space>
            </template>
            <template #toolsButtons>
              <a-space>
                <vxe-button status="primary"  @click="setScoreList">刷新</vxe-button>
              </a-space>
            </template>

            <template #default_level="{ row }">
              <span>{{ formatLevelLabel(row.level) }}</span>
            </template>
            <template #action="{ row }">
              <template v-if="hasScoresEditStatus(row)">
                <vxe-button mode="text" @click="saveScoresRowEvent(row)">保存</vxe-button>
                <vxe-button mode="text" @click="cancelScoresRowEvent()">取消</vxe-button>
              </template>
              <template v-else>
                <vxe-button mode="text" @click="editScoresRowEvent(row)" v-show="curSelectConfig.code">编辑</vxe-button>
                <vxe-button mode="text" icon="vxe-icon-delete" @click="handleScoresDelete(row)" v-show="curSelectConfig.code"></vxe-button>
              </template>
            </template>
          </vxe-grid>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import  { VxeGridProps,VXETable } from 'vxe-table'
import { listCriteria,listScores,listConfig,saveOrUpdate,saveOrUpdateConfig,saveOrUpdateScores,
  deleteOneConfig,deleteOne,deleteOneScores,computeData} from './AuditCriteria.api';

const loading = ref([false,false,false])
const leftWidth = ref(7)
const gridRef = ref()
const gridConfigRef = ref()
const gridScoresRef = ref()
const computeFormula = ref()

const curSelectCriteria = ref({})
const curSelectConfig = ref({})
const curSelectScore = ref({})

const criteriaGridOptions = reactive<VxeGridProps<any>>({
  border:true,
  height:"auto",
  columnConfig: {
    resizable: true
  },
  columns: [
    { field: 'code', title: '编码',editRender: { name: 'VxeInput' }  },
    { field: 'name', title: '名称',editRender: { name: 'VxeInput' }  },
    { field: 'weight', title: '权重',editRender: { name: 'VxeInput' } },
    { field: 'des', title: '说明',editRender: { name: 'VxeInput' } },
    { title: '操作', slots: { default: 'action' },width:"140" }
  ],
  editConfig: {
    trigger: 'dblclick',
    mode: 'row'
  },
  toolbarConfig: {
    zoom: true,
    slots: {
      buttons: 'toolbarButtons',
      tools:"toolsButtons"
    },
  },
  data: []
})

const configGridOptions = reactive<VxeGridProps<any>>({
  border:true,
  height:"auto",
  columnConfig: {
    resizable: true
  },
  columns: [
    { type: 'seq', width: 70 },
    { field: 'criteriaId', title: '模型',visible:false },
    { field: 'name', title: '名称',editRender: { name: 'VxeInput' } },
    { field: 'code', title: '编码' ,editRender: { name: 'VxeInput' } },
    { field: 'minval', title: '最小' ,editRender: { name: 'VxeInput' } },
    { field: 'maxval', title: '最大' ,editRender: { name: 'VxeInput' } },
    { title: '操作', slots: { default: 'action' },width:"140" }
  ],
  editConfig: {
    trigger: 'dblclick',
    mode: 'row'
  },
  toolbarConfig: {
    zoom: true,
    slots: {
      buttons: 'toolbarButtons',
      tools:"toolsButtons"
    },
  },
 
  data: []
})

const scoresGridOptions = reactive<VxeGridProps<any>>({
  border:true,
  height:"auto",
  columnConfig: {
    resizable: true
  },
  columns: [
    { type: 'seq', width: "5%" },
    { field: 'id', title: 'id',visible:false },
    { field: 'code', title: '编码',width:"15%"  },
    { field: 'codeName', title: '名称',},
    // { field: 'col1', title: '模型1' },
    // { field: 'col2', title: '模型1值' },
    // { field: 'col3', title: '模型2' },
    // { field: 'col4', title: '模型2值' },
    { field: 'val', title: '值',editRender: { name: 'VxeInput' } ,width:"15%" },
    { field: 'level', title: '等级', slots: { default: 'default_level' } ,width:"15%" },
    { title: '操作', slots: { default: 'action' },width:"20%" }
  ],
  editConfig: {
    trigger: 'dblclick',
    mode: 'row'
  },
  toolbarConfig: {
    zoom: true,
    slots: {
      buttons: 'toolbarButtons',
      tools:"toolsButtons"
    },
  },

  data: []
})

async function setCriteriaList() {
  loading.value[0] = true
  const resData = await listCriteria({})
  criteriaGridOptions.data = resData
  loading.value[0] = false
  
}

async function setConfigList(row) {
  curSelectCriteria.value = row
  loading.value[1] = true
  const resData = await listConfig({criteriaId:row?.id})
  configGridOptions.data = resData
  loading.value[1] = false
  if(row.code) {
    const $table = gridRef.value
    if ($table) {
      $table.setCurrentRow(row)
    }
  }

}

async function setScoreList(row) {
  curSelectConfig.value = row
  loading.value[2] = true
  let params = {}
  if(row.criteriaId) {
     params = {code:"*"+row.criteriaId+"_"+row.code+"*"}
  }
  const resData = await listScores(params)
  scoresGridOptions.data = processArray(resData);
  loading.value[2] = false

}

function processArray(arr) {
    return arr.map(item => {
        const codes = item.code.replace(/[_-]/g, '').split('').map(Number);
        return {
            col1: codes[0],
            col2: codes[1],
            col3: codes[2],
            col4: codes[3],
            ...item
        };
    });
}

async function handleAdd() {
  criteriaGridOptions.data?.unshift({

  })
}

async function handleAddConfig() {
  configGridOptions.data?.unshift({

  })
}

async function handleAddScores() {
  scoresGridOptions.data?.unshift({

  })
}

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 saveRowEvent = async(row) => {
  const $grid = gridRef.value
  if ($grid) {
   
    $grid.clearEdit().then(async() => {
      criteriaGridOptions.loading = true
      await saveOrUpdate(row,row.id?true:false);
      setTimeout(() => {
        criteriaGridOptions.loading = false
      }, 300)
    })
  }
}

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


const hasConfigEditStatus = (row) => {
  const $grid = gridConfigRef.value
  if ($grid) {
    return $grid.isEditByRow(row)
  }
}

const editConfigRowEvent = (row) => {
  const $grid = gridConfigRef.value
  if ($grid) {
    $grid.setEditRow(row)
  }
}

const saveConfigRowEvent = async(row) => {
  const $grid = gridConfigRef.value
  if ($grid) {
    if(!curSelectCriteria.value.code) {
      VXETable.modal.message({
        content: '请选择模型', 
        status: 'warning' })
      return;
    }
    $grid.clearEdit().then(async() => {
      row["criteriaId"] = curSelectCriteria.value.code
      criteriaGridOptions.loading = true
      await saveOrUpdateConfig(row,row.id?true:false);
      setTimeout(() => {
        criteriaGridOptions.loading = false
      }, 300)
    })
  }
}

const cancelConfigRowEvent = () => {
  const $grid = gridConfigRef.value
  if ($grid) {
    $grid.clearEdit()
  }
}


const hasScoresEditStatus = (row) => {
  const $grid = gridScoresRef.value
  if ($grid) {
    return $grid.isEditByRow(row)
  }
}

const editScoresRowEvent = (row) => {
  const $grid = gridScoresRef.value
  if ($grid) {
    $grid.setEditRow(row)
  }
}

const saveScoresRowEvent = async(row) => {
  const $grid = gridScoresRef.value
  if ($grid) {
    $grid.clearEdit().then(async() => {
      criteriaGridOptions.loading = true
      await saveOrUpdateScores(row,row.id?true:false);
      setTimeout(() => {
        criteriaGridOptions.loading = false
        setScoreList(curSelectConfig.value)
      }, 300)
    })
  }
}

const cancelScoresRowEvent = () => {
  const $grid = gridScoresRef.value
  if ($grid) {
    $grid.clearEdit()
  }
}

const handleCriteraDelete = async (row) => {
  let params = {id:row.id};
  await deleteOne(params,async function(){
    await setCriteriaList({});
  })
}
const handleConfigDelete = async (row) => {
  let params = {id:row.id};
  await deleteOneConfig(params,async function(){
    await setCriteriaList();
  })
}

const handleScoresDelete = async (row) => {
  let params = {id:row.id};
  await deleteOneScores(params,async function(){
    await setScoreList({});
  })
}

const handleComputeData = async () => {

  computeFormula.value =1
  //loading.value[2] = true
  await computeData({tp:computeFormula.value})
  await setScoreList({});
  //loading.value[2] = false
}

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

onMounted(() => {
  setCriteriaList();
  setConfigList({});
  setScoreList({});
})
</script>



