<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="项目名称" prop="projectName" v-if="!userStore.currentProId">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="试题描述" prop="questionDesc">
        <el-input
          v-model="queryParams.questionDesc"
          placeholder="请输入试题描述"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工种类型" prop="craftType" v-if="false">
        <el-select v-model="queryParams.craftType" placeholder="请选择工种类型" clearable>
          <el-option
            v-for="dict in pro_craft_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工种岗位" prop="craftPost">
        <el-select v-model="queryParams.craftPost" placeholder="请选择工种岗位" filterable clearable>
          <el-option
            v-for="dict in pro_craft_post"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
          <span style="float: left">{{ dict.label }}</span>
          <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px;">
            {{ findCraftPost(dict.elTagClass) }}
          </span>
        </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="试题类型" prop="questionType">
        <el-select v-model="queryParams.questionType" placeholder="请选择试题类型" clearable>
          <el-option
            v-for="dict in edu_question_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="试题范围" prop="questionScope" v-if="false">
        <el-select v-model="queryParams.questionScope" placeholder="请选择试题范围" clearable>
          <el-option
            v-for="dict in edu_question_scope"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </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-row :gutter="10" class="mb8">
      <el-col v-if="FirRoles=='admin'" :span="1.5">
        <el-button
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:busExamQuestion:add']"
        >新增通用试题</el-button>
      </el-col>
      <el-col v-if="FirRoles=='admin' || FirRoles=='gsAdmin'" :span="1.5">
        <el-button
          type="info"
          plain
          icon="Plus"
          @click="handleAddCom"
          v-hasPermi="['manage:busExamQuestion:add']"
        >新增公司试题</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAddProject"
          v-hasPermi="['manage:busExamQuestion:add']"
        >新增项目试题</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:busExamQuestion:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:busExamQuestion:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:busExamQuestion:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="busExamQuestionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="试题编号" align="center" prop="id" width="80"/>
      <el-table-column label="所属公司" align="center" prop="comName" width="120" :show-overflow-tooltip="true">
        <template #default="scope">
          <span v-if="scope.row.comId">{{scope.row.comName}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="center" prop="projectName" width="120" :show-overflow-tooltip="true">
        <template #default="scope">
          <span v-if="scope.row.projectId">{{scope.row.projectName}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="试题描述" align="center" prop="questionDesc"/>
      <el-table-column label="工种类型" align="center" prop="craftType" width="100" v-if="false">
        <template #default="scope">
          <dict-tag :options="pro_craft_type" :value="scope.row.craftType"/>
        </template>
      </el-table-column>
      <el-table-column label="工种岗位" align="center" prop="craftPost" width="450">
        <template #default="scope">
          <div class="flex gap-2">
            <el-tag
              v-for="dict in pro_craft_post"
              v-show="scope.row.craftPost.indexOf(dict.value)>-1"
              effect="dark"
            >
              {{ dict.label }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="试题类型" align="center" prop="questionType" width="80">
        <template #default="scope">
          <dict-tag :options="edu_question_type" :value="scope.row.questionType"/>
        </template>
      </el-table-column>
      <el-table-column label="试题范围" align="center" prop="questionScope" width="100" v-if="false">
        <template #default="scope">
          <dict-tag :options="edu_question_scope" :value="scope.row.questionScope"/>
        </template>
      </el-table-column>
      <el-table-column label="试题答案" align="center" prop="questionAnswer" width="100"/>
      <el-table-column label="是否启用" align="center" prop="isDel" width="88">
        <template #default="scope">
          <el-tooltip :content="scope.row.isDel == 0 ? '启用' : '停用'" placement="top">
            <el-switch
              :active-value="parseInt(0)"
              :inactive-value="parseInt(1)"
              v-model="scope.row.isDel"
              :disabled="scope.row.disabledState"
              @change="setStatus($event, scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-if="!scope.row.disabledState" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:busExamQuestion:edit']">修改</el-button>
          <el-button v-if="!scope.row.disabledState" link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:busExamQuestion:remove']">删除</el-button>
          <el-button v-if="scope.row.disabledState" type="danger" link disabled>-</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改基础题库对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="busExamQuestionRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属公司" v-if="form.comId">
          <el-tag effect="plain">{{ form.comName }}</el-tag>
        </el-form-item>
        <el-form-item label="项目名称" v-if="form.projectId">
          <el-tag effect="plain">{{ form.projectName }}</el-tag>
        </el-form-item>
        <el-form-item label="工种类型" prop="craftType" v-if="false">
          <el-select v-model="form.craftType" placeholder="请选择工种类型" style="width:100%" @change="changeCraftType">
            <el-option
              v-for="dict in pro_craft_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工种岗位" prop="craftPost">
          <el-cascader
                v-model="form.craftPost"
                :options="craftPostOptions"
                :props="casProps"
                style="width: 100%"
                placeholder="请选择工种岗位"
              />
        </el-form-item>
        <el-form-item label="试题类型" prop="questionType">
          <el-select v-model="form.questionType" placeholder="请选择试题类型" style="width:100%">
            <el-option
              v-for="dict in edu_question_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试题范围" prop="questionScope" v-if="false">
          <el-radio-group v-model="form.questionScope">
            <el-radio v-for="dict in edu_question_scope" :label="dict.value" border>{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="试题描述" prop="questionDesc">
          <el-input v-model="form.questionDesc" placeholder="请输入试题描述" type="textarea" rows="2" maxlength="64" show-word-limit/>
        </el-form-item>
        <el-divider content-position="center">试题答案信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddBusExamQuestionResult">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteBusExamQuestionResult">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="busExamQuestionResultList" :row-class-name="rowBusExamQuestionResultIndex" @selection-change="handleBusExamQuestionResultSelectionChange" ref="busExamQuestionResult">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="答案选项" prop="opt" width="105" align="center">
            <template #default="scope">
              <el-input v-model="scope.row.opt" placeholder="答案选项" maxlength="1"/>
            </template>
          </el-table-column>
          <el-table-column label="答案描述" prop="result">
            <template #default="scope">
              <el-input v-model="scope.row.result" placeholder="请输入答案描述" maxlength="128" show-word-limit/>
            </template>
          </el-table-column>
          <el-table-column label="正确答案" align="center" width="150">
            <template #default="scope">
              <el-checkbox
                v-model="scope.row.isOk"
                :checked="scope.row.isOk==1"
                label="正确答案"
                :true-label="parseInt(1)"
                :false-label="parseInt(0)"
                border
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BusExamQuestion">
import { listBusExamQuestion, getBusExamQuestion, delBusExamQuestion, addBusExamQuestion, updateBusExamQuestion } from "@/api/manage/busExamQuestion";
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance();
const { pro_craft_type, edu_question_type, sys_is_del, pro_craft_post, edu_question_diff, edu_question_scope } = proxy.useDict('pro_craft_type', 'edu_question_type', 'sys_is_del', 'pro_craft_post', 'edu_question_diff', 'edu_question_scope');

const userStore = useUserStore()
const busExamQuestionList = ref([]);
const busExamQuestionResultList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedBusExamQuestionResult = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const FirRoles = ref("");
const craftPostOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectName: null,
    craftType: null,
    craftPost: null,
    questionType: null,
    questionDesc: null,
    questionScope: null,
  },
  rules: {
    craftType: [{ required: true, message: "工种类型不能为空", trigger: "change" }],
    craftPost: [{ required: true, message: "工种岗位不能为空", trigger: "change" }],
    questionType: [{ required: true, message: "试题类型不能为空", trigger: "change" }],
    questionScope: [{ required: true, message: "试题范围不能为空", trigger: "change" }],
    questionDesc: [{ required: true, message: "试题描述不能为空", trigger: "blur" }]
  }
});

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

const casProps = {
  value: "value",
  label: "label",
  multiple: true,
};

/** 查询基础题库列表 */
function getList() {
  loading.value = true;
  if(!queryParams.value.craftType && queryParams.value.craftPost){
    queryParams.value.craftPost = null;
  }
  listBusExamQuestion(queryParams.value).then(response => {
    response.rows.forEach(item => {
      item.disabledState = initRowDisabled(item);
    })
    busExamQuestionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    comId: null,
    projectId: null,
    craftType: null,
    craftPost: null,
    questionDiff: null,
    questionType: null,
    questionDesc: null,
    questionScope: "1",
    questionAnswer: null,
    isDel: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  busExamQuestionResultList.value = [];
  proxy.resetForm("busExamQuestionRef");
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  initPost();
  open.value = true;
  title.value = "添加试题及答案";
}

/** 新增按钮操作 */
function handleAddCom() {
  if(!userStore.currentProId){
    proxy.$modal.msgWarning("请切换到项目数据！！！");
    return false;
  }
  reset();
  initPost();
  form.value.comId = userStore.currentComId;
  form.value.comName = userStore.currentComName;
  open.value = true;
  title.value = "添加试题及答案";
}

/** 新增按钮操作 */
function handleAddProject() {
  if(!userStore.currentProId){
    proxy.$modal.msgWarning("请切换到项目数据！！！");
    return false;
  }
  reset();
  initPost();
  form.value.comId = userStore.currentComId;
  form.value.comName = userStore.currentComName;
  form.value.projectId = userStore.currentProId;
  form.value.projectName = userStore.currentProName;
  open.value = true;
  title.value = "添加试题及答案";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  initPost();
  const _id = row.id || ids.value
  getBusExamQuestion(_id).then(response => {
    response.data.craftPost = JSON.parse(response.data.remark);
    form.value = response.data;
    busExamQuestionResultList.value = response.data.busExamQuestionResultList;
    open.value = true;
    title.value = "修改试题及答案";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["busExamQuestionRef"].validate(valid => {
    if (valid) {
      if (busExamQuestionResultList.value.length == 0) {
        proxy.$modal.msgError("请添加试题答案信息");
        return false;
      }
      let answer = [];
      //筛选正确答案信息
      busExamQuestionResultList.value.forEach((item,idx) => {
        if(!item.opt){
          proxy.$modal.msgError("请输入第"+(idx+1)+"个试题的答案选项");
          return false;
        }
        if(!item.result){
          proxy.$modal.msgError("请输入第"+(idx+1)+"个试题的答案描述");
          return false;
        }
        if (item.isOk != 0) {
          answer.push(item.opt);
        }
      });
      if (answer.length == 0) {
        proxy.$modal.msgError("请选择正确答案信息");
        return false;
      }
      form.value.remark = JSON.stringify(form.value.craftPost);
      let craftTypeValues = [];
      let craftPostValues = [];
      form.value.craftPost.forEach((item) => {
        if(craftTypeValues.indexOf(item[0])<0){
          craftTypeValues.push(item[0]);
        }
        craftPostValues.push(item[1]);
      });
      form.value.craftType = craftTypeValues.toString();
      form.value.craftPost = craftPostValues.toString();
      form.value.questionAnswer = answer.toString();
      form.value.busExamQuestionResultList = busExamQuestionResultList.value;
      if (form.value.id != null) {
        updateBusExamQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBusExamQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 启用状态滑块控制 */
function setStatus(val, row) {
  proxy.$modal
    .confirm(`是否确认${val == 0 ? "启用" : "停用"}当前数据项？`)
    .then(function () {
      let param = {'id': row.id, 'isDel': val};
      return updateBusExamQuestion(param);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("修改成功");
    })
    .catch(() => {
      // 取消时恢复原始开关状态
      if (val == 0) {
        row.isDel = 1;
      } else {
        row.isDel = 0;
      }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除基础题库编号为"' + _ids + '"的数据项？').then(function() {
    return delBusExamQuestion(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 题库试题序号 */
function rowBusExamQuestionResultIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 题库试题添加按钮操作 */
function handleAddBusExamQuestionResult() {
  let obj = {};
  obj.opt = "";
  obj.result = "";
  obj.isOk = 0;
  busExamQuestionResultList.value.push(obj);
}

/** 题库试题删除按钮操作 */
function handleDeleteBusExamQuestionResult() {
  if (checkedBusExamQuestionResult.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的题库试题数据");
  } else {
    const busExamQuestionResults = busExamQuestionResultList.value;
    const checkedBusExamQuestionResults = checkedBusExamQuestionResult.value;
    busExamQuestionResultList.value = busExamQuestionResults.filter(function(item) {
      return checkedBusExamQuestionResults.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleBusExamQuestionResultSelectionChange(selection) {
  checkedBusExamQuestionResult.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/busExamQuestion/export', {
    ...queryParams.value
  }, `busExamQuestion_${new Date().getTime()}.xlsx`)
}

/** 岗位类型改变 */
function changeCraftType() {
  form.value.craftPost = null;
}

/** 初始化行标识 */
function initRowDisabled(row) {
  let roles = userStore.roles;
  if(roles.includes("admin")){
    return false;
  }else if(roles.includes("gsAdmin") && row.comId){
    return false;
  }else if(row.projectId){
    return false;
  }else{
    return true;
  }
}

/** 初始化页面 */
function initPage() {
  let roles = userStore.roles;
  if(roles.includes("admin")){
    FirRoles.value = "admin";
  }else if(roles.includes("gsAdmin")){
    FirRoles.value = "gsAdmin";
  }else{
    FirRoles.value = "";
  }
}

/** 初始化岗位 */
function initPost() {
  let craftTypeDatas=pro_craft_type._object.pro_craft_type;
  let craftPostDatas=pro_craft_post._object.pro_craft_post;
  craftTypeDatas.forEach(item =>{
    item.children = craftPostDatas.filter(deatil=>deatil.elTagClass==item.value);
  });
  console.log("DEFAULT" , craftTypeDatas);
  craftPostOptions.value = craftTypeDatas;
}

// 搜索岗位类型
function findCraftPost(value) {
  let craftTypeDatas=pro_craft_type._object.pro_craft_type;
  for(let i=0;i<craftTypeDatas.length;i++){
    if(craftTypeDatas[i].value == value){
      return craftTypeDatas[i].label;
    }
  }
  return "-";
}

initPage();
getList();
</script>
<style lang="scss" scope>
.gap-2{
  .el-tag--default{
    margin:2px 3px;
  }
}
.el-divider__text{
  color: #409eff;
  font-weight: 800;
}
</style>