<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="selectedKey"
                  :showLine="false" @node-click="handleClick">
          <template #title="{ data }">
            <span :class="selectedKey == 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.username" 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="500" :columns="columns" :loading="loading" :default-toolbar="true"
                   :data-source="dataSource">
          <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" required mode="inline">
          <lay-form-item label="头像" prop="username">
            <lay-upload ref="uploadRef" :number="1" field="file" :size="1000" :headers="{ token: userStore.token }"
                        url="/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.avatar">
                  <img :src="model11.avatar" style="width: 100px;height: 100px"/>
                </div>
              </template>
            </lay-upload>
          </lay-form-item>
          <lay-form-item label="账户" prop="username">
            <lay-input v-model="model11.username" size="lg" placeholder="请输入账户"></lay-input>
          </lay-form-item>
          <lay-form-item label="密码" prop="password">
            <lay-input v-model="model11.password" size="lg" placeholder="请输入密码"></lay-input>
          </lay-form-item>
          <lay-form-item label="姓名" prop="nickname">
            <lay-input v-model="model11.nickname" size="lg" placeholder="请输入姓名"></lay-input>
          </lay-form-item>
          <lay-form-item label="手机号" prop="mobile">
            <lay-input v-model="model11.mobile" size="lg" placeholder="请输入手机号"></lay-input>
          </lay-form-item>
          <lay-form-item label="身份证号" prop="member_code">
            <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="work_number">
            <lay-input v-model="model11.work_number" size="lg" placeholder="请输入工号"></lay-input>
          </lay-form-item>
          <lay-form-item label="性别" prop="gender">
            <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="group_id">
            <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">
            <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">
            <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";

const cutUrl = ref("");
const uploadRef = ref(null)
import {useRouter} from 'vue-router'
import {useUserStore} from "@/store/user";

const userStore = useUserStore()
const replaceFields = {
  label: 'name',
  value: 'id',
  children: 'children'
}
const cutOptions = {
  copperOption: {
    center: false,
    aspectRatio: 1,
  }
}
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.avatar = date.data.fullurl;
  //uploadRef.value.submit()
};
onMounted(() => {
  getUserList();
  getLeftList();
  getPartyList();
  getAuthList();
})
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;
    } else {
      layer.msg(res.msg, {icon: 2})
    }
  })
}
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;
    } 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;
    } else {
      layer.msg(res.msg, {icon: 2})
    }
  })
}
//左侧
const data = ref([])
const selectedKey = ref('')
const isFold = ref(false)
const searchQuery = ref({
  username: '',
  mobile: '',
  gender: 0
})

function toReset() {
  searchQuery.value = {
    username: '',
    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: '100px', key: 'username',align: 'center'},
  {title: '姓名', width: '100px', key: 'nickname',align: 'center'},
  {title: '手机号', width: '120px', key: 'mobile',align: 'center'},
  {title: '工号', width: '150px', key: 'work_number',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 dataSource = ref([])

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

const addIsEdit = ref(1)
const addButton = ref([
  {
    text: "确认",
    callback: async () => {
      console.log(model11);
      //return;
      // 字段空值判断
      // if (!model11.username) {
      //   layer.msg('用户名不能为空！', {icon: 2});
      //   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.work_number) {
      //   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.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.username = row.username;
  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.id = row.id;
  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>
