<template>
  <MOSTY.PageTree :pageTitle="'师资库列表'" :searchType="'03'" @getDeptId="getdeptId">
    <template #serach>
      <el-divider />
      <MOSTY.Search :searchArr="searchArr" @submit="onSearch" />
      <el-divider />
      <section class="button">
        <el-button type="primary" @click="handleAddOrEdit('新增')">
          <el-icon>
            <Plus />
          </el-icon>
          <span>新增</span>
        </el-button>
      </section>
    </template>
    <template #table>
      <div style="height: calc(100vh - 378px);">
        <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading" :isSelect="false"
          :isSort="true" style="width: 100%;">
          <template #sex="{ row }">
            <span v-if="row.sex == '1'">男</span>
            <span v-else-if="row.sex == '2'">女</span>
            <span v-else>未知</span>
          </template>
          <template #teacherType="{ row }">
            {{ row.teacherType == '1' ? '外部师资' : '内部师资' }}
          </template>
          <template #actions="{ row }">
            <span class="operesee" @click="handleAddOrEdit('查看', row)"><el-icon>
                <View />
              </el-icon>详情</span>
            <span class="operedit" @click="handleAddOrEdit('修改', row)"><el-icon>
                <Edit />
              </el-icon>修改</span>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
              @confirm="handledelete(row)">
              <template #reference>
                <span class="operdel" size="small"><el-icon>
                    <Delete />
                  </el-icon>删除</span>
              </template>
            </el-popconfirm>
          </template>
        </MOSTY.Table>
      </div>
      <div class="fenye">
        <MOSTY.Pages :pageConfiger="listQuery" @changeSize="handleSizeChange" @changeNo="handleCurrentChange">
        </MOSTY.Pages>
      </div>
    </template>
  </MOSTY.PageTree>
  <!-- 新增修改查看 -->
  <el-dialog v-model="dialogVisible" :title="title" :before-close="closeDialog" width="800px">
    <div style='width:750px;height: calc(90vh - 200px);overflow-y: auto;'>
      <el-form ref="frombt" :model="dialogForm" :rules="rules" label-width="120px" style="display: block; width:100%;"
        label-suffix="：" :disabled="title.includes('查看')">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="dialogForm.name" style="width: 500px"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="dialogForm.sex" style="width: 500px" clearable placeholder="请选择性别">
            <el-option v-for="item in D_BZ_XB" :key="item" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="身份证" prop="idCode">
          <MOSTY.IdentityCard width="100%" v-model="dialogForm.idCode" clearable @onInput="identityCardChange"
            style="width: 500px">
          </MOSTY.IdentityCard>
          <!-- <el-input v-model="dialogForm.idCode" placeholder="请输入身份证" style="width: 500px"></el-input> -->
        </el-form-item>
        <el-form-item label="职称" prop="position">
          <!-- <el-select v-model="dialogForm.position" style="width: 500px" clearable placeholder="请选择职称">
              <el-option v-for="item in D_BZ_PYYYLX" :key="item" :label="item.label" :value="item.value" />
            </el-select> -->
          <el-input v-model="dialogForm.position" placeholder="请输入职称" style="width: 500px"></el-input>
        </el-form-item>
        <el-form-item label="擅长领域" prop="territory">
          <!-- <MOSTY.DictRidioAndSelect :dictData="D_BZ_AQRYSCLY" style="width: 500px" v-model="dialogForm.areasExpertiseCode" @onChange="handleScly"
              selectType="select" :multiple="false" placeholder="请选择" /> -->
          <el-input v-model="dialogForm.territory" placeholder="请输入擅长领域" style="width: 500px"></el-input>
        </el-form-item>
        <el-form-item label="证书上传" prop="file" style="width: 100%;">
          <MOSTY.Upload v-model="dialogForm.file" :limit="2" :ShowfileList="true" @filehandleChange="changeFile"
            :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" :isImg="true" />
        </el-form-item>
        <el-form-item label="个人图片" prop="cover" style="width: 100%;">
          <MOSTY.Upload v-model="dialogForm.cover" :limit="1" :ShowfileList="true" :isImg="true" />
        </el-form-item>
        <el-form-item label="师资类型" prop="teacherType">
          <el-select v-model="dialogForm.teacherType" style="width: 500px" clearable placeholder="师资类型">
            <el-option label="内部师资" value="0" />
            <el-option label="外部师资" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">

        <el-button type="primary" @click="saveFrom(frombt)" v-if="!title.includes('查看')" :loading="loading">
          <el-icon class="mr4">
            <DocumentChecked />
          </el-icon>
          保存
        </el-button>
        <el-button @click="closeDialog">
          <el-icon class="mr4">
            <DocumentDelete />
          </el-icon>关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
// 引入
import { ref, onMounted, reactive, watch, getCurrentInstance, nextTick } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, deleteApi, postApi } from "@/api/tobAcco_api.js";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
const { proxy } = getCurrentInstance();
const { D_BZ_XB } = proxy.$dict("D_BZ_XB");
const dialogVisible = ref(false);
const title = ref('')
const loading = ref(false);
const total = ref(0);
const frombt = ref();
const dialogForm = ref({});
const tableloading = ref(false);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 20,
  total: 0,
  teacherType: '',
});
//规则校验
const rules = reactive({
  idCode: [{ required: true, message: "身份证不能为空", trigger: "blur" }],
  ...rule.identityCardRule({ require: true, validator: true }, "idCode"),
  name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  sex: [{ required: true, message: "请选择性别", trigger: "change" }],
  teacherType: [{ required: true, message: "请选择师资类型", trigger: "change" }],
  position: [{ required: true, message: "职称不能为空", trigger: "blur" }],
  territory: [{ required: true, message: "擅长领域不能为空", trigger: "blur" }],
});
const tableColumn = ref([
  {
    title: "姓名",
    prop: "name",
  },
  {
    title: "性别",
    prop: "sex",
    slot: true
  },
  {
    title: "单位",
    prop: "orgname",
  },
  {
    title: "身份证",
    prop: "idCode",
  },
  {
    title: "师资类型",
    prop: "teacherType",
    slot: true
  },
  {
    title: "职称",
    prop: "position",
  },
  {
    title: "擅长领域",
    prop: "territory",
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const teacherType = [
  { value: '0', label: '内部师资' },
  { value: '1', label: '外部师资' },
]
const searchArr = reactive([
  {
    showType: "select",
    prop: "teacherType",
    width: '250px',
    placeholder: '请选择师资类型',
    options: teacherType,
  },
  {
    showType: "input",
    prop: "name",
    width: '250px',
    placeholder: '请输入姓名',
  },
]);
const tableData = ref([]);

const handleAddOrEdit = (type, row) => {
  dialogForm.value = {}
  if (type !== '新增') {
    getApi({ id: row.id }, "/mosty-jcgl/teacher/getInfo").then((res) => {
      dialogForm.value = res
      dialogForm.value.file = res.file.join(',')

    })
  }
  dialogVisible.value = true
  title.value = type + '师资'
}
//查询
function onSearch(obj) {
  listQuery.value.teacherType = obj.teacherType;
  listQuery.value.name = obj.name;
  listQuery.value.pageCurrent = 1;
  getTableData();
}
onMounted(() => {
  getTableData()
});

const closeDialog = () => {
  if (!title.value.includes('查看')) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        dialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    dialogVisible.value = false
  }

};

//	分页查询试卷列表
function getTableData() {
  tableloading.value = true;
  getApi(listQuery.value, "/mosty-jcgl/teacher/getList").then((res) => {
    if (res.records) {
      tableloading.value = false;
      tableData.value = res.records;
      total.value = res.total;
      listQuery.value.total = res.total;
    }
  }).catch(() => {
    tableData.value = [];
    tableloading.value = false;
  }).finally(() => {
    tableloading.value = false;
  });
}
//	保存师资
const saveFrom = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      if (dialogForm.value.cover && Array.isArray(dialogForm.value.cover)) {
        dialogForm.value.cover = dialogForm.value.cover.join(',');
      }
      if (typeof dialogForm.value.file == 'string') {
        dialogForm.value.file = dialogForm.value.file.split(',')
      }
      dialogForm.value.orgid = deptData.value.orgid;
      dialogForm.value.orgname = deptData.value.orgname;
      if (dialogForm.value.id) {
        postApi(dialogForm.value, '/mosty-jcgl/teacher/update').then((res) => {
          ElMessage.success('修改成功');
          dialogVisible.value = false;
          getTableData()
        }).finally(() => {
          loading.value = false
        })
      } else {
        postApi(dialogForm.value, '/mosty-jcgl/teacher/add').then((res) => {
          ElMessage.success('新增成功');
          dialogVisible.value = false;
          getTableData()
        }).finally(() => {
          loading.value = false
        })
      }
    } else {
      ElMessage.warning("请输入必填项");
    }
  })

}
//删除试卷信息
function handledelete(row) {
  deleteApi({}, `/mosty-jcgl/teacher/delete/${row.id}`).then((res) => {
    ElMessage.success("删除成功");
    getTableData();
  });
}
//页码发生变化
const handleCurrentChange = (val) => {
  listQuery.value.pageCurrent = val;
  getTableData();
};
//查询条数发生变化
const handleSizeChange = (val) => {
  listQuery.value.pageSize = val;
  getTableData();
};
const deptData = ref({
  orgid: '',
  orgname: '',
})
//获取部门参数
const getdeptId = (val) => {
  deptData.value.orgid = val.id;
  deptData.value.orgname = val.orgname;
  listQuery.value.orgid = val.id; // TODO: 先查所有
  listQuery.value.pageCurrent = 1;
  getTableData();
};
</script>

<style lang="scss" scoped>
.el-form {
  margin: 0 auto;
}


.toggle {
  height: 40px;
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #0f3916;

  .el-icon {
    transform: rotate(90deg);
    transition: all 0.25s ease;
  }

  &.active {
    .el-icon {
      transform: rotate(-90deg);
    }
  }
}

.button {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}
</style>
