<template>
  <lay-container fluid="true" class="organization-box">
    <div style="display: flex">
      <div :style="{ width: isFold ? `0px` : `300px` }" class="left-tree">
        <!-- tree -->
        <div v-show="!isFold">
          科室列表
        </div>
        <lay-tree v-show="!isFold" style="margin-top: 10px" :data="data" v-model:selectedKey="leftId" :showLine="false"
          @node-click="handleClick">
          <template #title="{ data }">
            <span :class="leftId == data.id ? 'isChecked' : ''">
              {{ data.name }}
            </span>
          </template>
        </lay-tree>
        <div class="isFold" @click="isFold = !isFold">
          &nbsp;<lay-icon v-if="!isFold" class="layui-icon-left"></lay-icon>
          <lay-icon v-else class="layui-icon-right"></lay-icon>
        </div>
      </div>
      <div style="flex: 1; padding: 10px; over-flow: auto">
        <!-- table -->
        <lay-card>
          <lay-form>
            <lay-row>
              <lay-col :md="5">
                <lay-form-item label="姓名" label-width="80">
                  <lay-input v-model="searchQuery.nickname" placeholder="请输入" size="sm" :allow-clear="true"
                    style="width: 98%"></lay-input>
                </lay-form-item>
              </lay-col>
              <lay-col :md="5">
                <lay-form-item label="手机号" label-width="80">
                  <lay-input v-model="searchQuery.mobile" placeholder="请输入" size="sm" :allow-clear="true"
                    style="width: 98%"></lay-input>
                </lay-form-item>
              </lay-col>
              <lay-col :md="5">
                <lay-form-item label="性别" label-width="80">
                  <lay-select class="search-input" size="sm" v-model="searchQuery.gender" :allow-clear="true"
                    placeholder="请选择">
                    <lay-select-option :value="0" label="未知"></lay-select-option>
                    <lay-select-option :value="1" label="男"></lay-select-option>
                    <lay-select-option :value="2" label="女"></lay-select-option>
                  </lay-select>
                </lay-form-item>
              </lay-col>
              <lay-col :md="5">
                <lay-form-item label-width="20">
                  <lay-button style="margin-left: 20px" type="normal" size="sm" @click="toSearch">
                    查询
                  </lay-button>
                  <lay-button size="sm" @click="toReset"> 重置</lay-button>
                </lay-form-item>
              </lay-col>
            </lay-row>
          </lay-form>
        </lay-card>
        <lay-table :page="page" height="600px" :columns="columns" :loading="loading" :default-toolbar="false"
          :data-source="dataSource" @change="changePage">
          <template #status="{ row }">
            <lay-tag type="danger" v-if="row.status == 0">已禁用</lay-tag>
            <lay-tag type="primary" v-if="row.status == 1">正常</lay-tag>
          </template>
          <template #gender="{ row }">
            <span v-if="row.gender == 0">未选择</span>
            <span v-if="row.gender == 1">男</span>
            <span v-if="row.gender == 2">女</span>
          </template>
          <template v-slot:toolbar>
            <lay-button size="sm" type="primary" @click="changeAddShow()">新增</lay-button>
          </template>
          <template v-slot:operator="{ row }">
            <lay-button size="xs" border="green" border-style="dashed" @click="edit(row)">
              编辑
            </lay-button>
            <lay-popconfirm trigger="click" content="确定要删除此用户吗?" @confirm="del(row)">
              <lay-button size="xs" border="red" border-style="dashed">删除</lay-button>
            </lay-popconfirm>
          </template>
        </lay-table>
      </div>
    </div>
    <lay-layer v-model="addShow" :title="title" :area="['750px', '100%']" :type="4" :shade="true" :btn="addButton">
      <div style="padding: 20px">
        <lay-form :model="model11" ref="layFormRef11" mode="inline">
          <lay-form-item label="证件照" prop="username">
            <lay-upload style="width:180px;" ref="uploadRefA" :number="1" field="file" :size="1000" :headers="{ token: userStore.token }"
              url="http://yfyd.hschool.com.cn/api/common/upload" @cutdone="getCutDone2" v-model="file2" :auto="true" acceptMime="images"
              :cut="false" :cutOptions="cutOptions" @done="getFileDone2">
              <template #preview>
                <div class="easy-wrap" v-if="model11.avatar">
                  <img :src="model11.avatar" style="width: 100px;" />
                </div>
              </template>
            </lay-upload>
          </lay-form-item>
          <lay-form-item label="工号" prop="code" required>
            <lay-input v-model="model11.code" size="lg" placeholder="请输入工号"></lay-input>
          </lay-form-item>
          <lay-form-item label="密码" prop="password" required>
            <lay-input v-model="model11.password" size="lg" placeholder="请输入密码"></lay-input>
          </lay-form-item>
          <lay-form-item label="姓名" prop="nickname" required>
            <lay-input v-model="model11.nickname" size="lg" placeholder="请输入姓名"></lay-input>
          </lay-form-item>
          <lay-form-item label="手机号" prop="mobile" required>
            <lay-input v-model="model11.mobile" size="lg" placeholder="请输入手机号"></lay-input>
          </lay-form-item>
          <lay-form-item label="身份证号" prop="member_code" required>
            <lay-input v-model="model11.member_code" size="lg" placeholder="请输入身份证号"></lay-input>
          </lay-form-item>
          <lay-form-item label="生日" prop="birthday">
            <lay-date-picker v-model="model11.birthday" placeholder="请选择生日" allow-clear
              style="width:180px;"></lay-date-picker>
          </lay-form-item>
          <lay-form-item label="邮箱" prop="email">
            <lay-input v-model="model11.email" size="lg" placeholder="请输入邮箱"></lay-input>
          </lay-form-item>
          <lay-form-item label="性别" prop="gender" required>
            <lay-select v-model="model11.gender" style="width:180px;">
              <lay-select-option :value="0" label="未选择"></lay-select-option>
              <lay-select-option :value="1" label="男"></lay-select-option>
              <lay-select-option :value="2" label="女"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <!-- 新增字段 -->
          <lay-form-item label="岗位名称" prop="position">
            <lay-input v-model="model11.position" size="lg" placeholder="请输入岗位名称"></lay-input>
          </lay-form-item>
          <lay-form-item label="业务性质" prop="business_nature">
            <lay-input v-model="model11.business_nature" size="lg" placeholder="请输入业务性质"></lay-input>
          </lay-form-item>
          <lay-form-item label="资格证图片" prop="username">
            <lay-upload style="width:180px;" ref="uploadRef" :number="1" field="file" :size="1000" :headers="{ token: userStore.token }"
              url="http://yfyd.hschool.com.cn/api/common/upload" @cutdone="getCutDone" v-model="file1" :auto="true" acceptMime="images"
              :cut="false" :cutOptions="cutOptions" @done="getFileDone">
              <template #preview>
                <div class="easy-wrap" v-if="model11.license_image">
                  <img :src="model11.license_image" style="width: 100px;" />
                </div>
              </template>
            </lay-upload>
          </lay-form-item>
          <lay-form-item label="资格证编码" prop="certificate_code">
            <lay-input v-model="model11.certificate_code" size="lg" placeholder="请输入资格证编码"></lay-input>
          </lay-form-item>
          <lay-form-item label="执业证编码" prop="license_code">
            <lay-input v-model="model11.license_code" size="lg" placeholder="请输入执业证编码"></lay-input>
          </lay-form-item>
          <lay-form-item label="行政职务" prop="administrative_position">
            <lay-input v-model="model11.administrative_position" size="lg" placeholder="请输入行政职务名称"></lay-input>
          </lay-form-item>
          <!-- 新增字段结束 -->
          <lay-form-item label="科室" prop="group_id" required>
            <lay-cascader :checkStrictly="false" size="lg" style="width:180px;" :options="data" search
              :replaceFields="replaceFields" v-model="model11.group_id" placeholder="选择科室" allow-clear></lay-cascader>
          </lay-form-item>
          <!-- <lay-form-item label="党支部" prop="party_id">
            <lay-cascader size="lg" style="width:180px;" :options="partyList" search
                          :replaceFields="replaceFields"
                          v-model="model11.party_id"
                          placeholder="选择党支部" allow-clear></lay-cascader>
          </lay-form-item> -->
          <lay-form-item label="角色组" prop="auth_group_id" required>
            <lay-select v-model="model11.auth_group_id" style="width:180px;" placeholder="选择角色组">
              <lay-select-option size="lg" v-for="item in authList" :value="item.id"
                :label="item.name"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <lay-form-item label="状态" prop="status" required>
            <lay-select v-model="model11.status" placeholder="请选择" size="lg" style="width:180px;">
              <lay-select-option :value="0" label="禁用"></lay-select-option>
              <lay-select-option :value="1" label="启用"></lay-select-option>
            </lay-select>
          </lay-form-item>
        </lay-form>
      </div>
    </lay-layer>
  </lay-container>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { layer } from '@layui/layui-vue';
import {
  authGroupData,
  userData,
  userDataAdd,
  userDataEdit,
  userDataDel,
  partyGroupData,
  userGroupData
} from "@/api/module/home";
import { useUserStore } from "@/store/user";

const cutUrl = ref("");
const uploadRef = ref(null)

const userStore = useUserStore()
const replaceFields = {
  label: 'name',
  value: 'id',
  children: 'children'
}
const cutOptions = {
  copperOption: {
    center: false,
    aspectRatio: 1,
  }
}
const file2 = ref([]);
const getCutDone2 = (res) => {
  console.log("getCutDone", res);
  cutUrl.value = res.msg;
};
const getFileDone2 = (res) => {
  var date = JSON.parse(res.data);
  console.log("getFileDone", date);
  model11.avatar = date.data.fullurl;
  //uploadRef.value.submit()
};

const file1 = ref([]);

const getCutDone = (res) => {
  console.log("getCutDone", res);
  cutUrl.value = res.msg;
};
const getFileDone = (res) => {
  var date = JSON.parse(res.data);
  console.log("getFileDone", date);
  model11.license_image = date.data.fullurl;
  //uploadRef.value.submit()
};
onMounted(() => {
  //getUserList();
  getLeftList();
  getPartyList();
  getAuthList();
})
const dataSource = ref([])

const getUserList = () => {
  userData({ group_id: leftId.value, size: page.limit, page: page.current }).then((res) => {
    console.log(res)
    if (res.code == 1) {
      dataSource.value = res.data.data;
      page.total = res.data.count;
    } else {
      dataSource.value = [];
      layer.msg(res.msg, { icon: 2 })
    }
  })
}
const changePage = (ppc) => {
  page.current = ppc.current;
  page.limit = ppc.limit;
  getUserList();
}
const partyList = ref([])
const getPartyList = () => {
  partyGroupData({}).then((res) => {
    console.log(res)
    if (res.code == 1) {
      partyList.value = res.data;
    } else {
      layer.msg(res.msg, { icon: 2 })
    }
  })
}
const leftId = ref(0);
const getLeftList = () => {
  userGroupData({}).then((res) => {
    console.log(res)
    if (res.code == 1) {
      data.value = res.data;
      // if (userStore.userInfo.level == 1) {
      //   data.value.unshift({ id: 0, name: '全部', children: [] })
      // }
      leftId.value = res.data[0].id;
      getUserList();
    } else {
      layer.msg(res.msg, { icon: 2 })
    }
  })
}
const authList = ref([])
const getAuthList = () => {
  authGroupData({}).then((res) => {
    console.log(res)
    if (res.code == 1) {
      //去除数组第一个值
      authList.value = res.data.slice(1);
    } else {
      layer.msg(res.msg, { icon: 2 })
    }
  })
}
//左侧
const data = ref([])
const selectedKey = ref('')
const isFold = ref(false)
const searchQuery = ref({
  nickname: '',
  mobile: '',
  gender: 0
})

function toReset() {
  searchQuery.value = {
    nickname: '',
    mobile: '',
    gender: 0
  }
}

function handleClick(node: any) {
  console.log(node);
  leftId.value = node.id
  getUserList();
}

const loading = ref(false)
const page = reactive({ current: 1, limit: 10, total: 1 })
const columns = ref([
  { title: '编号', width: '80px', key: 'id', align: 'center' },
  { title: '工号/帐号', width: '150px', key: 'code', align: 'center' },
  { title: '姓名', width: '100px', key: 'nickname', align: 'center' },
  { title: '手机号', width: '120px', key: 'mobile', align: 'center' },
  { title: '性别', width: '80px', key: 'gender', customSlot: 'gender', align: 'center' },
  { title: '身份证号', width: '180px', key: 'member_code', align: 'center' },
  { title: '状态', width: '100px', key: 'status', customSlot: 'status', align: 'center' },
  { title: '操作', width: '150px', customSlot: 'operator', key: 'operator', fixed: 'right', align: 'center' }
])
const change = (page: any) => {

}

const model11 = reactive({
  username: '',
  nickname: '',
  mobile: '',
  email: '',
  member_code: '',
  code: '',
  gender: 0,
  password: '',
  status: 1,
  auth_group_id: '',
  group_id: [],
  party_id: [],
  avatar: '',
  license_image:'',
  birthday: '',
  group_level: '',
  party_level: '',
  // 新增字段
  position: '',
  business_nature: '',
  certificate_code: '',
  license_code: '',
  administrative_position: '',
})
const layFormRef11 = ref()
const addShow = ref(false)
const title = ref('新增')
const changeAddShow = () => {
  addIsEdit.value = 1;
  // 重置表单数据
  Object.assign(model11, {
    username: '',
    nickname: '',
    mobile: '',
    email: '',
    member_code: '',
    license_image:'',
    code: '',
    gender: 0,
    id: 0,
    password: '',
    status: 1,
    auth_group_id: '',
    group_id: [],
    party_id: [],
    avatar: '',
    birthday: '',
    group_level: '',
    party_level: '',
    // 新增字段
    position: '',
    business_nature: '',
    certificate_code: '',
    license_code: '',
    administrative_position: '',
  });
  addShow.value = true;
}

const addIsEdit = ref(1)
const addButton = ref([
  {
    text: "确认",
    callback: async () => {
      console.log(model11);
      //return;
      // 字段空值判断
      if (!model11.nickname) {
        layer.msg('姓名不能为空！', { icon: 2 });
        return;
      }
      if (!model11.mobile) {
        layer.msg('手机号不能为空！', { icon: 2 });
        return;
      }
      // if (!model11.email) {
      //   layer.msg('邮箱不能为空！', {icon: 2});
      //   return;
      // }
      if (!model11.member_code) {
        layer.msg('身份证号不能为空！', { icon: 2 });
        return;
      }
      // if (!model11.birthday) {
      //   layer.msg('请选择生日！', {icon: 2});
      //   return;
      // }
      if (!model11.code) {
        layer.msg('工号不能为空！', { icon: 2 });
        return;
      }
      if (!model11.gender) {
        layer.msg('性别不能为空！', { icon: 2 });
        return;
      }
      if (!model11.auth_group_id) {
        layer.msg('角色组不能为空！', { icon: 2 });
        return;
      }
      if (!model11.status) {
        layer.msg('状态不能为空！', { icon: 2 });
        return;
      }
      if (!model11.group_id) {
        layer.msg('科室不能为空！', { icon: 2 });
        return;
      }
      // if (!model11.party_id) {
      //   layer.msg('党支部不能为空！', {icon: 2});
      //   return;
      // }
      model11.username = model11.code;
      model11.group_level = JSON.stringify(model11.group_id);
      model11.group_id = model11.group_id[model11.group_id.length - 1];
      console.log(model11.group_id)
      model11.party_level = JSON.stringify(model11.party_id);
      model11.party_id = model11.party_id[model11.party_id.length - 1];
      console.log(model11)
      if (addIsEdit.value == 1) {
        var res = await userDataAdd(model11);
      } else {
        var res = await userDataEdit(model11);
      }
      console.log(res)
      if (res.code == 1) {
        layer.msg('提交成功！', { icon: 1 })
        addShow.value = false;
        getUserList();
      } else {
        layer.msg(res.msg, { icon: 2 })
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      addShow.value = false;
    }
  }
])

// 搜索功能
const toSearch = () => {
  page.current = 1;
  change(page);
}

// 删除用户
const del = async (row: any) => {
  const res = await userDataDel({ id: row.id });
  if (res.code === 1) {
    layer.msg('删除成功', { icon: 1 });
    getUserList()
  } else {
    layer.msg(res.msg, { icon: 2 });
  }
}

// 编辑用户
const edit = (row: any) => {
  addIsEdit.value = 2;
  model11.gender = parseInt(row.gender);
  model11.status = parseInt(row.status);
  model11.auth_group_id = parseInt(row.auth_group_id);

  model11.group_id = JSON.parse(row.group_level);
  model11.party_id = JSON.parse(row.party_level);
  model11.code = row.code;
  model11.username = row.code;
  model11.nickname = row.nickname;
  model11.mobile = row.mobile;
  model11.email = row.email;
  model11.member_code = row.member_code;
  model11.work_number = row.work_number;
  model11.birthday = row.birthday;

  model11.avatar = row.avatar;
  model11.license_image = row.license_image;
  model11.id = row.id;

  // 新增字段赋值
  model11.position = row.position;
  model11.business_nature = row.business_nature;
  model11.certificate_code = row.certificate_code;
  model11.license_code = row.license_code;
  model11.administrative_position = row.administrative_position;

  console.log(model11)
  addShow.value = true;
}

</script>

<style scoped>
.organization-box {
  width: calc(100vw - 240px);
  height: calc(100vh - 110px);
  margin-top: 10px;
  box-sizing: border-box;
  background-color: #fff;
  overflow: hidden;
}

.left-tree {
  display: inline-block;
  padding: 20px 15px 0 5px;
  height: 1200px;
  border-right: 1px solid #e6e6e6;
  box-sizing: border-box;
  position: relative;
}

/* todo layui-tree-entry 设置无效 */
.layui-tree-entry {
  position: relative;
  padding: 10px 0;
  height: 20px;
  line-height: 20px;
  white-space: nowrap;
}

.isFold {
  position: absolute;
  top: 36%;
  right: -10px;
  width: 26px;
  height: 26px;
  line-height: 26px;
  border-radius: 13px;
  background-color: #fff;
  border: 1px solid #e6e6e6;
  cursor: pointer;
}

.search-input {
  display: inline-block;
  width: 98%;
  margin-right: 10px;
}

.isChecked {
  display: inline-block;
  background-color: #e8f1ff;
  color: red;
}
</style>
