<template>
  <div class="team-user-list">
    <el-skeleton :rows="10" animated v-if="!isLoaded" :throttle="500" />
    <div class="main-container" v-if="isLoaded">
      <el-form :model="currentRow.data" ref="editFormRef" :rules="editFormRules" inline-message :inline="false">
        <div class="top-screen">
          <h1>选择班组人员</h1>
          <el-form :model="screenForm" ref="screenFormRef" inline>
            <el-form-item label="姓名" prop="name">
              <div class="screen-item">
                <el-input v-model="screenForm.name"></el-input>
              </div>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <div class="screen-item">
                <el-input v-model="screenForm.mobile"></el-input>
              </div>
            </el-form-item>
            <el-form-item label="系统权限类型" prop="roleType">
              <div class="screen-item">
                <el-select v-model="screenForm.roleType" clearable>
                  <template v-for="(item, index) in selectItems['roleType']" :key="index">
                    <el-option :label="item.value" :value="item.key"></el-option>
                  </template>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="账号角色类型" prop="approle">
              <div class="screen-item">
                <el-select v-model="screenForm.approle" clearable>
                  <template v-for="(item, index) in selectItems['approle']" :key="index">
                    <el-option :label="item.value" :value="item.key"></el-option>
                  </template>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="search" size="small" @click="restSearch">查询</el-button>
              <el-button icon="Refresh" size="small" @click="clearScreen(screenFormRef)">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="main">
          <div class="main-left">
            <el-form-item label="人员列表"></el-form-item>
            <qu-table :tableData="tableData" v-model:tableHeader="tableHeader" :height="500" :rowButtons="[
              {
                enName: 'add',
                cnName: '选择人员',
                className: '',
              },
            ]" :pageProps="pageProps" @pageChange="pageChange" @sortChange="sortChange"
              @rowButtonClick="rowButtonClick" v-loading="tableLoading"></qu-table>
          </div>
          <div class="main-right">
            <el-form-item :label="'已选人员(' + selectUsersLength + ')'" prop="workMember"></el-form-item>
            <qu-table :tableData="selectWorkMember" v-model:tableHeader="selectTableHeader" :height="500"
              :showPage="false" showSelect v-loading="tableLoading" @selectionChange="chooseMember"
              ref="selectWorkMemberRef">
              <template #principalFlag="data">
                <el-select v-model="data.row.principalFlag" placeholder clearable filterable>
                  <el-option v-for="item in principalFlagArr" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </template>
            </qu-table>
          </div>
        </div>
      </el-form>

      <div style="width: 100%; padding: 15px 0; clear: both">
        <el-button @click="$emits('update:showSetPeopleForm', false)">取消</el-button>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks";
import { pageService } from "@/ApiService/pageService.js";
import { dropdownService } from "@/ApiService/dropdownService.js";
import {
  userService,
  workGroupService,
} from "@/ApiService/userCenterService.ts";

const props = defineProps({
  defaultProps: {
    type: Object,
    default: {
      buttonId: "",
      teamId: "",
    },
  },
  currentRow: {
    type: Object,
    default: () => { },
  },
  showSetPeopleForm: Boolean,
});
const selectUsersLength = computed(() => {
  return props.currentRow.data.workMember
    ? props.currentRow.data.workMember.length
    : 0;
});
const isLoaded = ref(true);
const tableLoading = ref(false);
const tableHeader = ref([]);
const selectItems = ref([]);
const editFormRef = ref();

const groupData = ref([]);
const principalFlagArr = ref([
  { id: 0, name: "否" },
  { id: 1, name: "是" },
]);
// 右侧已选人员表格表头
const selectTableHeader = ref([
  {
    enName: "name",
    cnName: "姓名",
    isTableShow: true,
  },
  {
    enName: "mobile",
    cnName: "手机号",
    isTableShow: true,
  },
  {
    enName: "principalFlag",
    cnName: "是否为负责人",
    isTableShow: true,
    fieldType: "custom",
  },
]);
// 设置班组人员表单规则
const editFormRules = {
  workMember: [
    { required: true, message: "请选择班组人员", trigger: "change" },
  ],
};
const selectWorkMemberRef = ref();
const selectWorkMember = ref([]);
const $emits = defineEmits(["OK", "update:showSetPeopleForm"]);
// 数据定义 end
const buttonClick = (button) => {
  buttonsClickFun.data[button.enName]();
};
// 选择人员逻辑
const rowButtonClick = ({ row, $column }) => {
  const key = selectWorkMember.value.some((item) => item.mobile == row.mobile);
  if (key) {
    $message.error("已选该人员");
    return;
  }
  selectWorkMember.value.push({ ...row, principalFlag: 0 });
  selectWorkMemberRef.value.toggleRowSelection(
    selectWorkMember.value[selectWorkMember.value.length - 1],
    true
  );
};
// 监听右侧选中人员变化
const chooseMember = (selection) => {
  props.currentRow.data.workMember = selection;
};
// 获取子页面字段
const fetchFields = () => {
  return new Promise((resolve) => {
    const { buttonId } = props.defaultProps;
    if (!buttonId) {
      $message.error("缺少参数");
      return;
    }
    pageService.queryButtonFieldByButton({ buttonId }).then((res) => {
      if (res.code == 0) {
        tableHeader.value = res.data;
        selectItems.value = $common.selectItems(tableHeader.value);
      } else {
        $message.error(res.err);
      }
    });
  });
};

// 获取左侧人员列表
const fetchData = () => {
  const { page, rows, sord, sidx } = pageProps;
  userService
    .userSelectList({
      page,
      rows,
      sord,
      sidx,
      districtId: props.currentRow.data.districtId,
      ...screenForm,
    })
    .then((res) => {
      if (res.code == 0) {
        tableData.value = res.data.rows;
        pageProps.records = res.data.records;
      } else {
        $message.error(res.err);
      }
    });
};
// 保存选中人员
const onSubmit = () => {
  console.log(props.currentRow.data);
  editFormRef.value.validate((rps) => {
    if (rps) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          const { workMember } = props.currentRow.data;
          const { teamId } = props.defaultProps;
          let workMembers = [];
          workMember.map((item) => {
            const { id, mobile, principalFlag, name } = item;
            workMembers.push({ id, mobile, principalFlag, name });
          });

          workGroupService
            .addorUpdateMember({ workGroupId: teamId, workMember: workMembers })
            .then((res) => {
              if (res.code == 0) {
                $message.success("操作成功");
                $emits("OK", true);
                $emits("update:showSetPeopleForm", false);
              } else {
                $message.error(res.err);
              }
            });
        });
    }
  });
};
// 获取右侧已选人员列表
const fetchMembers = () => {
  workGroupService
    .memberList({ workGroupId: props.defaultProps.teamId })
    .then((res) => {
      if (res.code == 0) {
        selectWorkMember.value = res.data;
        props.currentRow.data.workMember = res.data;
        nextTick(() => {
          selectWorkMember.value.map((item) => {
            selectWorkMemberRef.value.toggleRowSelection(item, true);
          });
        });
      } else {
        $message.error(res.err);
      }
    });
};
const {
  $route,
  $router,
  $store,
  $message,
  $messageBox,
  $common,
  tableData,
  screenForm,
  screenFormRef,
  pageProps,
  buttonsClickFun,
  pageChange,
  sortChange,
  restSearch,
  clearScreen,
} = templateHooks(fetchData);
// 函数定义 end
onMounted(() => {
  fetchFields();
  // 接收到父组件站点id 获取人员列表
  if (props.currentRow.data.districtId) {
    fetchData();
  }
  // 接收到父组件班组id 获取已选人员列表
  if (props.defaultProps.teamId) {
    fetchMembers();
  }
});
// 生命周期 end
</script>
<script>
export default {
  name: "chooseTeamUserForm",
};
</script>
<style lang="scss" scoped>
.main {
  width: 100%;

  .main-left {
    float: left;
    width: 60%;
  }

  .main-right {
    float: right;
    width: 38%;
  }
}
</style>
