<template>
  <div>
    <div class="search flex justify-between bg-white rounded-md">
      <el-form :inline="true" class="demo-form-inline" size="default">
        <el-form-item label="">
          <el-select v-model="form_query.sm_id" filterable clearable placeholder="全部学校" @change="initData">
            <el-option v-for="(item, index) in tableSchoolData" :key="index" :label="item.sm_name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-select placeholder="全部年级" v-model="form_query.user_grade_num" @change="initData" filterable clearable>
            <el-option v-for="(item, index) in tableGradeData" :key="index" :label="item.tjzn_njmc" :value="item.tjzn_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="form_query.subject_id" placeholder="全部学科" @change="initData" filterable clearable>
            <el-option v-for="(item, index) in tableSubjectData" :key="index" :label="item.tjzx_xkmc" :value="item.tjzx_id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="initData"> 查询 </el-button>
      </div>
    </div>
    <div class="bg-white rounded-md mt-4 px-23px py-16px">
      <div class="flex justify-between pb-4 btn">
        <div>
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="primary" @click="exportAll">导出</el-button>
          <import-button url="/user/main" :d="{ user_role_id: '75' }" @success="initData">
            <template #text>批量导入</template>
          </import-button>
          <el-button type="danger" @click="handleMulDelete" :disabled="multipleSelection.length == 0">删除</el-button>
        </div>
        <div class="flex content-center">
          <el-input v-model="form_query.keyword" class="w-40 mx-2" size="small" placeholder="请输搜索关键词" :suffix-icon="Search" clearable />
          <el-button type="primary" @click="initData">搜索</el-button>
        </div>
      </div>
      <el-table :data="tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="user_id" label="ID" width="100"></el-table-column>
        <el-table-column prop="user_name" label="账号" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="user_realname" label="姓名" width="150"></el-table-column>
        <el-table-column prop="sm_id" label="学校">
          <template #default="scope">
            <div v-for="item in tableSchoolData" :key="item.id">
              <span v-if="item.id == scope.row.sm_id">{{ item.sm_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="user_grade_num" label="年级"> </el-table-column>
        <el-table-column prop="subject_id" label="学科"> </el-table-column>
        <el-table-column label="操作" width="245">
          <template #default="scope">
            <el-button type="text" @click="handleDetail(scope.row.user_id)">详情 |</el-button>
            <el-button type="text" @click="handleEdit(scope.row)">编辑 |</el-button>
            <el-button type="text" @click="handleDelete(scope.row.user_id)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="flex justify-end my-10">
        <el-pagination v-model:current-page="form_query.page" v-model:page-size="form_query.limit" layout="total,sizes, prev, pager, next, jumper" :total="total" :background="true" @current-change="initData" :hide-on-single-page="false" />
      </div>

      <el-dialog v-model="dialogVisible" :title="title" width="780px">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize" status-icon>
          <h3 class="text-hex-00A3FF">账号信息</h3>
          <div class="flex">
            <el-form-item label="账号：" prop="user_name">
              <el-input class="rank" v-model="ruleForm.user_name" />
            </el-form-item>
            <el-form-item label="密码：" prop="user_password">
              <el-input class="rank" :disabled="isEdit" v-model="ruleForm.user_password" />
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="用户角色：" prop="user_role_id_sub">
              <el-select multiple collapse-tags v-model="userRoleData" filterable clearable @change="handleRoleChange">
                <el-option v-for="(item, index) in roleList" :key="index" :label="item.tur_role_name" :value="item.tur_id" />
              </el-select>
              <el-button type="primary" class="ml-100px" plain @click="setRoleDialogVisible = true">自定义角色</el-button>
            </el-form-item>
          </div>
          <h3 class="text-hex-00A3FF">基本信息</h3>
          <el-form-item label="头像：">
            <file-upload-progress v-if="dialogVisible" v-model:part="ruleForm.user_avatar" :limit="1" accept=".jpg,.jpeg,.webp,.png" :size-limit="500 * 1024">
              <el-button type="primary"> 点击上传 </el-button>
              <template #tip>
                <div class="mt-2 text-xs">
                  只能上传jpg/png文件，且不超过500kb，建议尺寸600x337
                </div>
              </template>
            </file-upload-progress>
          </el-form-item>
          <el-form-item label="头像地址：" class="w-640px" prop="user_avatar">
            <el-input v-model="ruleForm.user_avatar" />
          </el-form-item>
          <div class="flex">
            <el-form-item label="姓名：" prop="user_realname">
              <el-input class="rank" v-model="ruleForm.user_realname" />
            </el-form-item>
            <el-form-item label="性别：" prop="gender">
              <el-radio-group v-model="ruleForm.gender">
                <el-radio label="1">男</el-radio>
                <el-radio label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <div class="flex">
            <el-form-item label="学校：" prop="sm_id">
              <el-select v-model="ruleForm.sm_id" filterable clearable placeholder="全部学校">
                <el-option v-for="(item, index) in tableSchoolData" :key="index" :label="item.sm_name" :value="item.id" />
              </el-select>
            </el-form-item>
          </div>
          <div class="total mb-5">
            <el-form-item v-for="(p, i) in officeData" :key="i" label-width="0">
              <div class="flex justify-between">
                <div class="w-100px text-center">
                  <div class="text-hex-00A3FF" v-if="i == 0">任职信息一</div>
                  <div class="text-hex-00A3FF" v-if="i > 0">
                    成员信息{{ dealFigureToChinese(i + 1) }}
                  </div>
                </div>
                <div class="w-565px">
                  <div class="h-40px w-full justify-end flex items-center">
                    <el-icon @click="deleteOffice(i)" color="#409eff" size="20px">
                      <Delete />
                    </el-icon>
                  </div>
                  <div class="w-full office">
                    <span>年级：</span>
                    <remote-select v-model:model-name="p.grade_name" v-model="p.grade_id" to="jcxxgl_zyflgl_nj" :fields="['tjzn_id', 'tjzn_njmc']"></remote-select>
                  </div>
                  <div class="flex office">
                    <span class="mr-10px text-right">学科:</span>
                    <remote-select v-model:model-name="p.xueke_name" v-model="p.xueke_id" to="jcxxgl_zyflgl_xk" :fields="['tjzx_id', 'tjzx_xkmc']"></remote-select>
                    <span class="mr-10px ml-60px text-right">任教班级:</span>
                    <remote-select v-model="p.class_id" to="jcxxgl_zyflgl_bj" v-model:model-name="p.class_name" :fields="['tjzb_id', 'tjzb_bjmc']"></remote-select>
                  </div>
                </div>
              </div>
            </el-form-item>

            <el-button class="ml-100px" @click="addOffice" type="primary" plain>添加</el-button>
          </div>
          <el-form-item label="爱好特长：" class="w-640px" prop="about">
            <el-input type="textarea" v-model="ruleForm.about" />
          </el-form-item>
          <h3 class="text-hex-00A3FF">联系方式</h3>
          <div class="flex">
            <el-form-item label="联系电话：" prop="user_phone">
              <el-input class="rank" v-model="ruleForm.user_phone" />
            </el-form-item>
            <el-form-item label="电子信箱：" prop="user_email">
              <el-input class="rank" v-model="ruleForm.user_email" />
            </el-form-item>
          </div>
        </el-form>
        <div class="text-center">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(ruleFormRef)">
            确定
          </el-button>
        </div>
      </el-dialog>

      <el-dialog v-model="setRoleDialogVisible" class="_" width="565" destroy-on-close title="自定义角色" @close="handleClose">
        <el-form class="table" ref="ruleFormRef1" :model="roleData" :rules="roleRules">
          <el-form-item label="角色名：" prop="tur_role_name" class="w-270px">
            <el-input size="small" v-model="roleData.tur_role_name" type="text" />
          </el-form-item>
          <el-form-item label="" prop="tur_role_menu">
            <div class="w-full">设置权限：</div>
            <menu-item v-model="roleData.tur_role_menu"></menu-item>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="flex_center space-x-12">
            <el-button size="large" @click="handleClose">取消</el-button>
            <el-button size="large" type="primary" @click="PermissionSubmit(ruleFormRef1)">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>

      <el-dialog v-model="detailDialogVisible" class="_" width="778" title="详情">
        <img class="avatar" :src="ruleForm.user_avatar" />
        <el-form class="grid grid-cols-2" ref="ruleFormRef" label-position="right" label-width="90px" :model="detailForm">
          <el-form-item label="账号:">
            {{ detailForm.user_name }}
          </el-form-item>
          <el-form-item label="用户角色:">
            {{ detailForm.role_name }}
          </el-form-item>
          <el-form-item label="姓名:">
            {{ detailForm.user_realname }}
          </el-form-item>
          <el-form-item label="性别:">
            {{ detailForm.gender1 }}
          </el-form-item>
          <el-form-item label="学校:">
            <div v-for="item in tableSchoolData" :key="item.id">
              <span v-if="item.id == detailForm.sm_id">{{ item.sm_name }}</span>
            </div>
          </el-form-item>
          <el-form-item label="任职信息:" class="col-span-full">
            <div v-for="item in officeData" :key="item">
              <span class="mr-30px">
                {{ item.grade_name }}{{ item.class_name
                }}{{ item.xueke_name }}</span>
            </div>
          </el-form-item>
          <el-form-item label="特长:" class="col-span-full">
            {{ detailForm.about }}
          </el-form-item>
          <el-form-item label="联系电话:">
            {{ detailForm.user_phone }}
          </el-form-item>
          <el-form-item label="电子邮件:">
            {{ detailForm.user_email }}
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="flex_center space-x-12">
            <el-button size="large" type="primary" @click="handleFormCancel">返回</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import {
  Search,
  Delete,
  Download,
  Plus,
  ZoomIn,
} from "@element-plus/icons-vue";
import { user } from "@/store/index";
import MenuItem from "~/pages/manage/yhxx/jsgl/MenuItem.vue";
import {
  yhxx_js_list,
  yhxx_js_del,
  yhxx_js_add,
  yhxx_js_edit,
  yhxx_js_detail,
  school_list,
  grade_list,
  class_list,
  subject_list,
  role_list,
  role_add,
} from "./api";
const ruleFormRef = ref(null);
const ruleFormRef1 = ref(null);
let tableData = $ref([]);
let detailForm = $ref({});

let rules = $ref({
  user_name: [{ required: true, message: "请输入账号", trigger: "submit" }],
  //user_password: [{ required: true, message: "请输入密码", trigger: "submit" }],
  user_realname: [{ required: true, message: "请输入姓名", trigger: "submit" }],
  gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  sm_id: [{ required: true, message: "请选择学校", trigger: "blur" }],
});
let roleRules = $ref({
  tur_role_name: [
    { required: true, message: "请输入角色名", trigger: "submit" },
  ],
  tur_role_menu: [{ required: true, message: "请选择菜单", trigger: "submit" }],
});
let total = $ref(10);
let form_query = $ref({
  page: 1,
  limit: 6,
  keyword: "",
  user_role_id: "75",
  user_grade_num: "",
  sm_id: "",
  subject_id: "",
  issubmit: 1,
});

let officeData = $ref([
  {
    grade_id: "",
    grade_name: "",
    class_id: "",
    class_name: "",
    xueke_id: "",
    xueke_name: "",
  },
]);

//学校列表
let tableSchoolData = $ref([]);
function initSchoolData() {
  school_list({ limit: 100 }).then((res) => {
    if (res.code === "1") {
      tableSchoolData = res.data.page_data;
    }
  });
}
initSchoolData();
//年级列表
let tableGradeData = $ref([]);
function initGradeData() {
  grade_list({ limit: 100 }).then((res) => {
    if (res.code === "1") {
      tableGradeData = res.data.page_data;
    }
  });
}
initGradeData();
//学科列表
let tableSubjectData = $ref([]);
function initSubjectData() {
  subject_list({ limit: 100 }).then((res) => {
    if (res.code === "1") {
      tableSubjectData = res.data.page_data;
    }
  });
}
initSubjectData();
//班级列表
let tableClassData = $ref([]);
function initClassData() {
  class_list({ limit: 100 }).then((res) => {
    if (res.code === "1") {
      tableClassData = res.data.page_data;
    }
  });
}
//角色列表
let roleList = $ref([]);
function initRoleData() {
  role_list({ limit: 100, M5jxrcL: "" }).then((res) => {
    if (res.code === "1") {
      roleList = res.data.page_data;
    }
  });
}
let multipleSelection = $ref([]);
let handleSelectionChange = (val) => {
  multipleSelection = [];
  val.forEach((i) => {
    multipleSelection.push(i.user_id);
  });
};

let roleData = $ref({
  tur_role_name: "",
  tur_role_menu: "",
});
//添加额外权限
let setRoleDialogVisible = $ref(false);

let detailDialogVisible = ref(false);
let detailData = ref({});
//详情

function handleDetail(id) {
  const data = {
    user_id: id,
  };
  yhxx_js_detail(data).then((res) => {
    if (res.code === "1") {
      detailData = res.data;
      detailForm = {
        user_role_id: "75",
        user_name: detailData.user_name,
        user_realname: detailData.user_realname,
        role_name: detailData.role_name,
        user_avatar: detailData.user_avatar,
        gender: detailData.gender,
        gender1:
          detailData.gender == 1
            ? "男"
            : detailData.gender == 2
              ? "女"
              : "保密",
        sm_id: detailData.sm_id,
        user_phone: detailData.user_phone,
        user_email: detailData.user_email,
        address: detailData.address,
        about: detailData.about,
        ue_jbxx_tea_rzxx: detailData.ext.ue_jbxx_tea_rzxx,
      };

      if (detailData.user_role_id_ext) {
        userRoleData = detailData.user_role_id_ext.split(",");
      }

      let m = res.data.ext.ue_jbxx_tea_rzxx;
      if (m != "" && m != undefined && m != null) {
        officeData = JSON.parse(m);
      }

      Object.keys(ruleForm).find((item) => {
        ruleForm[item] = detailForm[item];
      });
      if (!dialogVisible) {
        detailDialogVisible.value = true;
      }
    }
  });
}
//列表

let rzInfo = $ref([]);
function initData() {
  const data = {
    ...form_query,
  };
  yhxx_js_list(data).then((res) => {
    if (res.code == "1") {
      tableData = res.data.page_data;
      total = res.data.total_rows * 1;
      tableData.map((i) => {
        let arr1 = [];
        let arr2 = [];
        let m = i.ext.ue_jbxx_tea_rzxx;
        console.log(m === undefined, m === null, 44444444444);
        if (m != "" && m != undefined && m != null) {
          rzInfo = JSON.parse(m);
        }
        console.log(rzInfo, 55);
        if (rzInfo) {
          rzInfo.map((val) => {
            arr1.push(val.grade_name);
            arr2.push(val.xueke_name);
          });
        }

        i.user_grade_num = arr1.join(" ");
        i.subject_id = arr2.join(" ");
      });
    }
  });
}
initData();
const userRoleData = $ref([]);
let ruleForm = $ref({
  user_name: "",
  user_password: "",
  user_avatar: "",
  user_realname: "",
  gender: "",
  sm_id: "",
  ue_jbxx_tea_rzxx: "",
  user_phone: "",
  user_email: "",
  about: "",
  user_role_id: "75",
  user_role_id_sub: "",
});

function handleRoleChange(val) {
  ruleForm.user_role_id_sub = val.join();
}

//新增
let dialogVisible = $ref(false);
let title = $ref("");
let isEdit = $ref(false);
//添加
function handleAdd() {
  initRoleData();
  initClassData();
  dialogVisible = true;
  title = "新增";
  isEdit = false;
  ruleForm = {
    user_name: "",
    user_password: "",
    user_avatar: "",
    user_realname: "",
    gender: "",
    sm_id: "",
    user_phone: "",
    user_email: "",
    about: "",
    user_role_id: "75",
    user_role_id_sub: "",
  };
  officeData = [
    {
      grade_id: "",
      grade_name: "",
      class_id: "",
      class_name: "",
      xueke_id: "",
      xueke_name: "",
    },
  ];
}
// 添加任职信息
function addOffice() {
  officeData.push({
    grade_id: "",
    grade_name: "",
    class_id: "",
    class_name: "",
    xueke_id: "",
    xueke_name: "",
  });
}
// 删除任职信息
function deleteOffice(index) {
  officeData.splice(index, 1);
}

//编辑
let currentId = $ref("");
function handleEdit(row) {
  initRoleData();

  initClassData();
  title = "编辑";
  isEdit = true;
  currentId = row.user_id;
  handleDetail(row.user_id);
  dialogVisible = true;
}

const handleSubmit = async (formEl) => {
  if (!formEl) return;

  formEl.validate(async (valid, fields) => {
    if (valid) {
      let flag = false;
      let a = [];
      officeData.map((item) => {
        let b = {};
        if (!item.grade_id || !item.class_id || !item.xueke_id) {
          flag = true;
        } else {
          b = {
            grade_id: item.grade_id,
            grade_name: item.grade_name,
            class_id: item.class_id,
            class_name: item.class_name,
            xueke_id: item.xueke_id,
            xueke_name: item.xueke_name,
          };
        }

        a.push(b);
      });
      console.log(a, 111111111);
      if (flag) {
        return ElMessage({
          type: "warning",
          message: "请填写完整任职信息",
        });
      }

      const data = {
        user_main: {
          user_role_id: "75",
          user_role_id_sub: ruleForm.user_role_id_sub,
          user_name: ruleForm.user_name,
          user_password: ruleForm.user_password,
          user_avatar: ruleForm.user_avatar,
          user_realname: ruleForm.user_realname,
          gender: ruleForm.gender,
          sm_id: ruleForm.sm_id,
          user_phone: ruleForm.user_phone,
          user_email: ruleForm.user_email,
          about: ruleForm.about,
          ue_jbxx_tea_rzxx: JSON.stringify(a),
        },
      };

      if (!isEdit) {
        if (!data.user_main.user_password) {
          return ElMessage({
            type: "warning",
            message: "请输入密码",
          });
        }
        yhxx_js_add(data).then((res) => {
          if (res.code == 1) {
            ElMessage({
              message: "添加成功",
              type: "success",
            });
            dialogVisible = false;
            initData();
          } else {
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }
        });
      } else {
        data.user_id = currentId;

        yhxx_js_edit(data).then((res) => {
          if (res.code == 1) {
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
            dialogVisible = false;
            initData();
          } else {
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
// 批量删除
function handleMulDelete() {
  ElMessageBox.confirm("确认删除这些数据?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = { user_id: multipleSelection };
      yhxx_js_del(data).then((res) => {
        if (res.code == 1) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          initData();
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
      });
    })
    .catch(() => { });
}
//单个删除
function handleDelete(id) {
  ElMessageBox.confirm("确认删除?", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      let data = { user_id: id };
      yhxx_js_del(data).then((res) => {
        if (res.code == 1) {
          ElMessage({
            message: "删除成功",
            type: "success",
          });
          initData();
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
      });
    })
    .catch(() => { });
}
function exportAll() {
  let ids = multipleSelection.join(",");

  let link =
    window.GLOBAL_CONFIG.api +
    "/user/main/index?user_role_id=75&api=xls&page=1&limit=10000&token=" +
    user.value.token +
    "&user_id=" +
    ids;
  console.log(link);
  window.open(link, "_blank");
}
function handleFormCancel() {
  detailDialogVisible.value = false;
}

const PermissionSubmit = async (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const data = {
        txwx_user_role: {
          tur_role_name: roleData.tur_role_name,
          tur_role_menu: roleData.tur_role_menu,
        },
      };
      role_add(data).then((res) => {
        if (res.code == 1) {
          ElMessage({
            message: "添加成功",
            type: "success",
          });
          handleClose();
          initRoleData();
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
      });
    }
  });
};

const handleClose = () => {
  setRoleDialogVisible = false;
  roleData = {
    tur_role_name: "",
    tur_role_menu: "",
  };
};
</script>
<style lang="scss" scoped>
.search {
  height: 72px;
  line-height: 85px;
  padding: 0 29px;
}
.avatar {
  width: 82px;
  height: 82px;
  background: #c4c4c4;
  border-radius: 8px;
  margin: 30px auto 50px;
}
:deep() .el-dialog__body {
  padding-left: 60px;
  border-top: 1px solid #f3f3f3;
}
.btn {
  border-bottom: 1px solid #e3e3e3;
}

.office {
  margin: 20px 0;
  :deep() .el-form-item__content {
    width: 196px;
  }
  :deep() .el-input {
    width: 196px;
  }
}
</style>