<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="'100%'" :columns="columns" :loading="loading" :default-toolbar="true"
                   :data-source="dataSource" v-model:selected-keys="selectedKeys" @change="change"
                   @sortChange="sortChange">
          <template #status="{ row }">
            <lay-switch :model-value="row.status" @change="changeStatus($event, row)"></lay-switch>
          </template>
          <template #role="{ row }">
            <lay-tag color="#165DFF" variant="light">{{ row.role }}</lay-tag>
          </template>

          <template v-slot:toolbar>
            <lay-button size="sm" type="primary" @click="changeAddShow()">新增</lay-button>
            <lay-button size="sm" @click="toRemove">删除</lay-button>
          </template>
          <template v-slot:operator="{ row }">
            <lay-button size="xs" border="green" border-style="dashed">编辑
            </lay-button>
            <lay-popconfirm content="确定要删除此用户吗?" @confirm="confirm" @cancel="cancel">
              <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" @cutcancel="getCutCancel" :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" v-if="title === '新增'">
            <lay-input type="password" 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="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 size="lg" style="width:180px;" :options="data" search :replaceFields="{ label:'name',value:'id',children:'children'}" 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="{ label:'name',value:'id',children:'children'}" 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="1" label="禁用"></lay-select-option>
              <lay-select-option :value="2" 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, menuData, menuDataAdd, menuDataEdit, 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 groupList= ref([]);
const cutOptions = {
  copperOption: {
    center: false,
    aspectRatio: 1,
  }
}
const file1 = ref([]);
const getCutDone=(res)=>{
  console.log("getCutDone",res);
  cutUrl.value = res.msg;
};

const getCutCancel=(res)=>{
  console.log("getCutCancel",res);
};

const getFileDone=(res)=>{

  var date= JSON.parse(res.data);
  console.log("getFileDone",date);
  model11.avatar = date.data.fullurl;
  //uploadRef.value.submit()
};
onMounted(()=>{
  console.log(userStore.token);
  getLeftList();
  getPartyList();
  getAuthList();
})
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 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 selectedNode = ref({
  id: 0,
  title: ''
})
const isFold = ref(false)
const searchQuery = ref({
  username: '',
  mobile: '',
  gender: 0
})

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

function handleClick(node: any) {
  selectedNode.value = JSON.parse(JSON.stringify(node))
  page.current = selectedNode.value.id
  change(page)
}
const loading = ref(false)
const selectedKeys = ref()
const page = reactive({current: 1, limit: 10, total: 100})
const columns = ref([
  {title: '选项', width: '55px', type: 'checkbox', fixed: 'left'},
  {title: '编号', width: '80px', key: 'id', fixed: 'left', sort: 'id'},
  {title: '用户名', width: '100px', key: 'username', sort: 'username'},
  {title: '昵称', width: '100px', key: 'nickname'},
  {title: '手机号', width: '120px', key: 'mobile'},
  {title: '邮箱', width: '150px', key: 'email'},
  {
    title: '性别', width: '80px', key: 'gender',
    customSlot: 'gender',
    render: (row: any) => {
      return row.gender === 1 ? '男' : row.gender === 2 ? '女' : '未知'
    }
  },
  {title: '身份证号', width: '180px', key: 'member_code'},
  {
    title: '创建时间', width: '160px', key: 'createtime',
    render: (row: any) => {
      return new Date(row.createtime * 1000).toLocaleString()
    }
  },
  {title: '状态', width: '100px', key: 'status', customSlot: 'status'},
  {
    title: '操作',
    width: '150px',
    customSlot: 'operator',
    key: 'operator',
    fixed: 'right'
  }
])
const change = (page: any) => {
  loading.value = true
  setTimeout(() => {
    dataSource.value = loadDataSource(page.current, page.limit)
    loading.value = false
  }, 1000)
}
const sortChange = (key: any, sort: number) => {
  layer.msg(`字段${key} - 排序${sort}, 你可以利用 sort-change 实现服务端排序`)
}
const dataSource = ref([])
const changeStatus = (isChecked: boolean, row: any) => {
  dataSource.value.forEach((item) => {
    if (item.id === row.id) {
      layer.msg('Success', {icon: 1}, () => {
        item.status = isChecked
      })
    }
  })
}
const remove = () => {
  layer.msg(selectedKeys.value, {area: '50%'})
}
const loadDataSource = (page: number, pageSize: number) => {
  var response = []
  var startIndex = (page - 1) * pageSize + 1
  var endIndex = page * pageSize
  for (var i = startIndex; i <= endIndex; i++) {
    response.push({
      id: `${i}`,
      account: `user${i}`,
      sex: '男',
      name: `用户${i}`,
      joinTime: '2022-02-09 18:34:56',
      role: '普通用户',
      status: true
    })
  }
  return response
}
const model11 = reactive({
  username: '',
  nickname: '',
  mobile: '',
  email: '',
  member_code: '',
  work_number: '',
  gender: 0,
  password: '',
  status: 1,
  auth_group_id: '',
  group_id: '',
  party_id: '',
  avatar: ''
})
const layFormRef11 = ref()
const addShow = ref(false)
const title = ref('新增')
const changeAddShow = () => {
  addShow.value = true;
}
const submit11 = function () {
  layFormRef11.value.validate((isValidate: any, model: any, errors: any) => {
    layer.open({
      type: 1,
      title: '表单提交结果',
      content: `<div style="padding: 10px"><p>是否通过 : ${isValidate}</p> <p>表单数据 : ${JSON.stringify(
          model
      )} </p> <p>错误信息 : ${JSON.stringify(errors)}</p></div>`,
      shade: false,
      isHtmlFragment: true,
      btn: [
        {
          text: '确认',
          callback(index: any) {
            layer.close(index)
          }
        }
      ],
      area: '500px'
    })
  })
}
// 清除校验
const clearValidate11 = function () {
  layFormRef11.value.clearValidate()
}
// 重置表单
const reset11 = function () {
  layFormRef11.value.reset()
}

function toRemove() {
  if (selectedKeys.value.length == 0) {
    layer.msg('您未选择数据，请先选择要删除的数据', {icon: 3, time: 2000})
    return
  }
  layer.confirm('您将删除所有选中的数据？', {
    title: '提示',
    btn: [
      {
        text: '确定',
        callback: (id: any) => {
          layer.msg('您已成功删除')
          layer.close(id)
        }
      },
      {
        text: '取消',
        callback: (id: any) => {
          layer.msg('您已取消操作')
          layer.close(id)
        }
      }
    ]
  })
}

function toSubmit() {
  layer.msg('保存成功！', {icon: 1, time: 1000})
  visible11.value = false
  visible22.value = false
}

function toCancel() {
  visible11.value = false
  visible22.value = false
}

function confirm() {
  layer.msg('您已成功删除')
}

function cancel() {
  layer.msg('您已取消操作')
}

const model22 = ref({
  organization: '',
  name: '',
  fullName: '',
  code: '',
  type: '',
  sort: 0,
  remark: ''
})
const visible22 = ref(false)
const addButton = ref([
  {
    text: "确认",
    callback: async () => {
      console.log(model11);
      // if (addData.title == '') {
      //   layer.msg('菜单名称不能为空！', { icon: 2 })
      //   return;
      // }
      // if (addIsEdit.value == 1) {
      //   addData.name=addData.title;
      //   var res = await menuDataAdd(addData);
      // } else {
      //   var res = await menuDataEdit(addData);
      // }
      // console.log(res)
      // if (res.code == 1) {
      //   layer.msg('提交成功！', { icon: 1 })
      //   addShow.value = false;
      //   getHierarchicalData();
      // } else {
      //   layer.msg(res.msg, { icon: 2 })
      // }
    }
  },
  {
    text: "取消",
    callback: () => {
      //addShow.value = false;
    }
  }
])
</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>
