﻿<template>
  <div class="chooseUser-container">
    <el-dialog v-model="isShowDialog" width="80%" draggable="" :before-close="closeDialog" destroy-on-close :fullscreen="fullScreen">
      <template #header>
        <div style="color: #fff;display: flex;align-items: center;justify-content: space-between;">
          <span>{{ props.title }}</span>
          <el-icon size="16" @click="fullScreen = !fullScreen" style="margin-right: 16px; display: block; vertical-align: middle;cursor: pointer">
            <ele-FullScreen v-if="!fullScreen" />
            <ele-Notification v-else />
          </el-icon>
        </div>
      </template>
      <el-row :gutter="10" style="height: 100%;">
        <el-col :span="4">
          <treeFilter ref="orgTreeRef" @node-click="nodeClick" />
        </el-col>
        <el-col :span="20" style="display: flex;flex-direction: column;">
          <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
            <el-form :model="queryParams" ref="queryForm" :inline="true">
              <el-form-item label="账号">
                <el-input v-model="queryParams.account" placeholder="账号" clearable />
              </el-form-item>
              <el-form-item label="姓名">
                <el-input v-model="queryParams.realName" placeholder="姓名" clearable />
              </el-form-item>
              <el-form-item label="手机号码">
                <el-input v-model="queryParams.phone" placeholder="手机号码" clearable />
              </el-form-item>
              <el-form-item label="状态">
                <el-select clearable v-model="queryParams.status" placeholder="请选择状态">
                  <el-option :value="1" label="启用"></el-option>
                  <el-option :value="0" label="停用"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button-group>
                  <el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'sysUser/page'"> 查询
                  </el-button>
                  <el-button icon="ele-Refresh" @click="() => queryParams = {}"> 重置 </el-button>
                </el-button-group>
              </el-form-item>
            </el-form>
          </el-card>
          <el-card class="full-table" shadow="hover" style="margin-top: 8px">
            <el-table :data="tableData" ref="tableRef" style="width: 100%" v-loading="loading"
                      tooltip-effect="light" row-key="id" border="" @selection-change="onSelectionChange">
              <el-table-column type="selection" :reserve-selection="true" v-if="props.isAny" width="55"
                               align="center" />
              <el-table-column type="index" label="序号" width="55" align="center" />

              <el-table-column label="头像" width="80" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <el-avatar :src="scope.row.avatar" size="small">{{ scope.row.nickName?.slice(0, 1) ??
                  scope.row.realName?.slice(0, 1) }} </el-avatar>
                </template>
              </el-table-column>
              <el-table-column prop="account" label="账号" width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="realName" label="姓名" width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="phone" label="手机号码" width="120" align="center" show-overflow-tooltip />
              <el-table-column label="账号类型" width="110" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <el-tag v-if="scope.row.accountType === 888"> 系统管理员 </el-tag>
                  <el-tag v-else-if="scope.row.accountType === 777"> 普通账号 </el-tag>
                  <el-tag v-else-if="scope.row.accountType === 666"> 会员 </el-tag>
                  <el-tag v-else> 其他 </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="roleName" label="角色集合" min-width="130" align="center"
                               show-overflow-tooltip />
              <el-table-column prop="orgName" label="所属机构" min-width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="posName" label="职位名称" min-width="120" align="center" show-overflow-tooltip />
              <el-table-column prop="orderNo" label="排序" width="70" align="center" show-overflow-tooltip />

              <el-table-column label="操作" width="140" align="center" fixed="right"
                               show-overflow-tooltip="" v-if="!props.isAny">
                <template #default="scope">
                  <el-button icon="ele-Edit" size="small" text="" type="primary"
                             @click="selectOne(scope.row)"> 选择 </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize"
                           :total="tableParams.total" :page-sizes="[10, 20, 50, 100, 200, 500]" small="" background=""
                           @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           layout="total, sizes, prev, pager, next, jumper" />


          </el-card>
        </el-col>
      </el-row>
      <template #footer v-if="props.isAny">
                <span class="dialog-footer">
                    <el-button @click="cancel">取 消</el-button>
                    <el-button type="primary" @click="confirm">确 定（{{ selectionNum }}条）</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup="" name="mesMaterial">
import {nextTick, ref} from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { auth } from '/@/utils/authFunction';
import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
import { formatDate } from '/@/utils/formatTime';


//import treeFilter from '/@/businessComponents/components/orgTree.vue'
//import treeFilter from './component/component/orgTree.vue'
import treeFilter from './component/orgTree.vue'
import {getAPI} from "/@/utils/axios-utils";
import {SysUserApi} from "/@/api-services";
import {pageMesProductionLine} from "/@/api/mes/mesProductionLine";

var props = defineProps({
  title: {
    type: String,
    default: "",
  },
  isAny: {
    type: Boolean,
    default: false,
  },
});

const showAdvanceQueryUI = ref(true);
const loading = ref(false);
const tableData = ref<any>([]);
const queryParams = ref<any>({});
const tableParams = ref({
  page: 1,
  pageSize: 10,
  total: 0,
  Field:'resourceCode',
  Order:'asc',
});
let fullScreen = ref(false);
const tableRef = ref<any>();
const isShowDialog = ref(false);
const options = ref<any>({});
//已选择的条数
const selectionNum = ref<number>(0);

//父级传递来的函数，用于回调
const emit = defineEmits(["finish"]);

// 打开弹窗
let orgTreeRef = ref();
const productionLineCode = ref();
const codes = ref();
const openDialog = async (_options: any) => {
  queryParams.value.orgId=undefined;
  if(_options && _options.productionLineCode){
    productionLineCode.value = _options.productionLineCode;
  }else{
    productionLineCode.value = null;
  }
  if(_options && _options.codes){
    codes.value = _options.codes;
  }else{
    codes.value = null;
  }

  console.log(_options)
  isShowDialog.value = true;
  nextTick(()=>{
    console.log(_options?.factoryCode);
    if(_options?.factoryCode){
      orgTreeRef.value.getTreeData().then(res=>{
        let list = res.data.result ?? [];
        console.log(list);
        let flag = list.find(item=> item?.factoryName == _options?.factoryCode);
        if(flag){
          queryParams.value.orgId = flag?.orgInfo?.id;
          handleQuery(true);
        }
      })
    }else{
      handleQuery(true);
    }
  })

};

// 关闭弹窗
const closeDialog = () => {
  isShowDialog.value = false;
  tableRef.value.clearSelection();
};

// 取消
const cancel = () => {
  isShowDialog.value = false;
  tableRef.value.clearSelection();
};

//确定
const confirm = () => {
  emit("finish", { rows: tableRef.value.getSelectionRows() });
  isShowDialog.value = false;
}
// 选择一个
const selectOne = (row: any) => {
  emit("finish", row);
  isShowDialog.value = false;
}

// 选择行变更
const onSelectionChange = () => {
  selectionNum.value = tableRef.value.getSelectionRows().length;
}

// 查询操作
const handleQuery = async (first?: boolean) => {
  loading.value = true;
  // 查询产线关联的【上岗资质】里的人员
  if(productionLineCode.value){
    let data = (await pageMesProductionLine({productionLineCode:productionLineCode.value})).data.result?.items ?? [];
    if(data[0]){
      tableData.value = (data[0].personCodes || '')
          .split(',')
          .filter((item) => item)
          .map((item, index) => {
            return {
              account: item || '',
              realName: (data[0].personNames || '').split(',').filter((item) => item)?.[index] || '',
            };
          });
      tableParams.value.total = 0;
      loading.value = false;
    }else{
    }
    return
  }

  // 查询系人员清单
  let params = Object.assign(Object.assign(queryParams.value, tableParams.value));
  console.log(queryParams.value.orgId);
  if(queryParams.value.orgId==undefined)
  {
    params.orgId=codes.value;
  }
  var res = await getAPI(SysUserApi).apiSysUserPagePost(params);
  tableData.value = res.data.result?.items ?? [];
  console.log(tableData.value);
  tableParams.value.total = <number>res.data.result?.total;
  loading.value = false;
};

// 改变页面容量
const handleSizeChange = (val: number) => {
  tableParams.value.pageSize = val;
  handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
  tableParams.value.page = val;
  handleQuery();
};
// 点击树形筛选
const typeClick = (item: any) => {
  queryParams.value.ResourceTypeCode = item.resourceTypeCode;
  handleQuery();
}

// 树组件点击
const nodeClick = async (node: any) => {
  queryParams.value.orgId = node.id;
  queryParams.value.account = undefined;
  queryParams.value.realName = undefined;
  queryParams.value.phone = undefined;
  handleQuery();
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
<style scoped>
:deep(.el-ipnut),
:deep(.el-select),
:deep(.el-input-number) {
  width: 100%;
}
</style>
