<!--
@ 作者: 秦东
@ 时间: 2023-08-21 14:41:41
@ 备注: 选择用户
-->
<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from "vue";
import { getRequest } from "@/api/DesignForm";
import formatResult from "@/utils/DesignForm/formatResult";
import {
  getOrgFormTree,
  getOrgFormUserList,
  searchUserCustomerFormList,
} from "@/api/hr/org/index";
import { orgform, criteriaForPeopleList } from "@/api/hr/org/type";
import UserRole from "@/assets/icons/user.svg";

const props = withDefaults(
  defineProps<{
    modelValue?: string;
  }>(),
  {}
);
const emits = defineEmits<{
  (e: "update:modelValue", value: string): void;
}>();
const visible = ref(false);
// 侧栏处理
const treeEl = ref();
const treeData = ref<orgform[]>([]);
const department = ref(309);
const handleNodeClick = (data: any) => {
  department.value = data.id;
  getUserList();
};
const getTreeData = () => {
  // getRequest('deptList', {}).then((res: any) => {
  //   treeData.value = formatResult(res.data, 'transformDataToChild')
  // })
  getOrgFormTree({ id: 309 })
    .then(({ data }) => {
      // console.log(data)
      treeData.value = data.list;
    })
    .finally(() => {});
};
// 侧栏处理结束
const userName = ref();
const tableData = ref<criteriaForPeopleList[]>();
const page = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
});
const searchClick = () => {
  getUserList();
};
const resetClick = () => {
  userName.value = "";
  department.value = "";
  treeEl.value.setCurrentKey(null);
  getUserList();
};
const getUserList = () => {
  const params = {
    pageInfo: {
      pageIndex: page.current,
      pageSize: page.pageSize,
    },
    name: userName.value,
    department: department.value,
  };
  // getRequest('userList', params).then((res: any) => {
  //   	tableData.value = res.data.list
  // })
  // getOrgFormUserList
  getOrgFormUserList(params)
    .then(({ data }) => {
      tableData.value = data.list;
      page.total = data.total;
    })
    .finally(() => {});
};
const currentChange = (current: number) => {
  page.current = current;
  getUserList();
};
//　已选
// const checkData = ref<any>([]);

const checkDataList = reactive<criteriaForPeopleList[]>([]);

const tableRowClick = (row: any) => {
  if (checkDataList.length > 0) {
    let isIn = true;
    checkDataList.forEach((item) => {
      if (item.id == row.id) {
        isIn = false;
      }
    });
    if (isIn) {
      checkDataList.push(row);
    }
  } else {
    checkDataList.push(row);
  }
  // console.log("checkDataList",checkDataList,row)
};
const delRowClick = (row: criteriaForPeopleList) => {
  // console.log("checkDataList",row)
  // checkData.value.forEach((item: any, index: number) => {
  // 	if (item === row) {
  // 		checkData.value.splice(index, 1)
  // 	}
  // })
  if (checkDataList && checkDataList.length > 0) {
    checkDataList.forEach((item: criteriaForPeopleList, index: number) => {
      if (item.id == row.id) {
        checkDataList.splice(index, 1);
      }
    });
  }

  // let checkDataAry = checkDataList
  // if(checkDataAry.length > 0) {
  // 	checkDataList.splice(0,checkDataList.length)
  // 	console.log("checkDataList----1------>",checkDataAry,checkDataList)
  // 	checkDataAry.forEach(item => {
  // 		if(item.id != row.id){
  // 			console.log("checkDataList---------->",item)
  // 			checkDataList.push(item)
  // 		}
  // 	})
  // }
};
const delAllClick = () => {
  // checkData.value = []
  checkDataList.splice(0, checkDataList.length);
};
// 弹窗处理
const open = () => {
  visible.value = true;
  // console.log("open--->",props.modelValue)
  if (props.modelValue) {
    searchUserCustomerFormList({ name: props.modelValue }).then(({ data }) => {
      // console.log("弹窗处理",data)
      // checkDataList = data
      checkDataList.splice(0, checkDataList.length);
      if (data.length > 0) {
        data.forEach((item: any) => {
          checkDataList.push(item);
        });
      }
    });
    // checkData.value = props.modelValue.split(',')
    // let jsonCont:criteriaForPeopleList[]  = JSON.parse(props.modelValue)
    // if(jsonCont.length > 0) {
    // 	checkDataList.splice(0,checkDataList.length)
    // 	jsonCont.forEach(item=>{
    // 		checkDataList.push(item)
    // 	})
    // }
  } else {
    checkDataList.splice(0, checkDataList.length);
  }
};
// 关闭弹窗
const confirmClick = () => {
  // emits('update:modelValue', checkData.value.join(','))
  let jsonStr = JSON.stringify(checkDataList);
  emits("update:modelValue", jsonStr);
  visible.value = false;
};
defineExpose({ open });
onMounted(() => {
  nextTick(() => {
    // 可根据实际情况放在点击打开弹窗后加载，会出现loading
    getTreeData();
    getUserList();
  });
});

const defaultProps = {
  children: "children",
  label: "name",
};
</script>
<template>
  <el-dialog
    title="用户选择"
    v-model="visible"
    :append-to-body="true"
    :props="defaultProps"
    width="80%"
    top="2vh"
    draggable
  >
    <el-row :gutter="20">
      <el-col :span="6" style="padding: 0">
        <div class="sidebar_tree">
          <el-tree
            ref="treeEl"
            :data="treeData"
            node-key="id"
            @node-click="handleNodeClick"
            :props="defaultProps"
            highlight-current
          />
        </div>
      </el-col>
      <el-col :span="12">
        <div class="search">
          <el-input placeholder="请输入用户名" v-model="userName" />
          <el-button type="primary" @click="searchClick">查询</el-button>
          <el-button @click="resetClick">重置</el-button>
        </div>
        <div class="list">
          <el-table :data="tableData" style="width: 100%; height: 710px">
            <el-table-column prop="userName" label="照片" width="100px" align="center">
              <template #default="scope">
                <el-avatar
                  v-if="scope.row.icon != ''"
                  shape="square"
                  :size="30"
                  :src="scope.row.icon"
                />
                <el-avatar v-else shape="square" :size="30" :src="UserRole" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="120px" align="left">
              <template #default="scope">
                {{ scope.row.name }}({{ scope.row.number }})
              </template>
            </el-table-column>
            <el-table-column prop="tel" label="联系方式" width="120px" align="left" />
            <el-table-column prop="nickName" label="归属行政组织" align="left">
              <template #default="{ row }">
                {{ row.companyname
                }}<span v-if="row.maindeparmentname != ''">
                  / {{ row.maindeparmentname }}</span
                >
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60px">
              <template #default="{ row }">
                <el-button circle size="small" @click="tableRowClick(row)"
                  ><el-icon><ArrowRight /></el-icon
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="page">
            <el-pagination
              background
              layout="prev, pager, next, jumper"
              small
              hide-on-single-page
              :current-page="page.current"
              :total="page.total"
              :page-size="page.pageSize"
              @current-change="currentChange"
            />
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="has_select">
          <div class="total">
            <div>已选择：{{ checkDataList.length }}</div>
            <el-button type="danger" @click="delAllClick" size="small"
              >全部移除</el-button
            >
          </div>
          <el-table :data="checkDataList" style="height: 710px">
            <el-table-column prop="userName" label="照片" width="60px" align="center">
              <template #default="scope">
                <el-avatar
                  v-if="scope.row.icon != ''"
                  shape="square"
                  :size="30"
                  :src="scope.row.icon"
                />
                <el-avatar v-else shape="square" :size="30" :src="UserRole" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" align="left">
              <template #default="scope">
                {{ scope.row.name }}({{ scope.row.number }})
              </template>
            </el-table-column>
            <el-table-column label="操作" width="60px">
              <template #default="{ row }">
                <el-button size="small" type="danger" @click="delRowClick(row)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>

    <template #footer>
      <div>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="confirmClick"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.sidebar_tree {
  width: 100%;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  padding: 10px 0;
  margin-right: 10px;
  height: 750px;
  overflow-y: auto;
}
.has_select {
  width: 100%;

  .total {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 32px;
    margin-bottom: 10px;
  }
}
.search {
  display: flex;
  margin-bottom: 10px;
  .el-input {
    margin-right: 10px;
  }
}
.page {
  padding-top: 20px;
  display: flex;
  justify-content: space-between;
}
.expand-user-dialog {
  display: flex;
  align-items: flex-start;
  .sidebar-tree {
    width: 180px;
    border: 1px solid #ebeef5;
    border-radius: 3px;
    padding: 10px 0;
    margin-right: 10px;
    max-height: 500px;
    overflow-y: auto;
  }
  .table-list {
  }
  .search {
    display: flex;
    margin-bottom: 10px;
    .el-input {
      margin-right: 10px;
    }
  }
  .page {
    padding-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  .has-select {
    width: 200px;
    margin-left: 20px;
    .total {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 32px;
      margin-bottom: 10px;
    }
  }
}
</style>
