<template>
	<a-modal :visible='showAddModal' :title="$t('plan.team-members.staff-query-add-page')" @ok='handleAddSubmit'
			 @cancel='handleCancel' width='60%'>
		<a-card class='search-wrapper mb-2' :bordered='false'>
			<a-form layout='vertical' :form='form'>
				<a-row :gutter='24'>
					<a-col :lg='9' :md='24' :sm='24'>
						<a-form-item :label="$t('plan.team-members.name-or-account')">
							<a-input allowClear v-model='form.userName'
									 :placeholder="$t('plan.team-members.enter-a-name-or-account')"></a-input>
						</a-form-item>
					</a-col>
					<a-col :lg='15' :md='24' :sm='24'>
            <a-form-item class="pull-right" :label="'\xa0'">
              <a-button type='default' class="ml-2 mr-2" @click='reset'>
                {{ $t('plan.team-members.reset') }}
              </a-button>
              <a-button class='searchBtn' type='primary' @click='search'>{{ $t('plan.team-members.search') }}
              </a-button>
            </a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-card>
		<a-tabs :activeKey='tabKey' @change="callback" tabPosition='left'>
			<a-tab-pane :key="'1'" :tab="$t('plan.team-members.dfmea-project-member')">
				<a-card class='table-wrapper'>
					<a-table
						:rowSelection="{
						selectedRowKeys: projectSelectedRowKeys,
						onChange: onMemberAddSelectChange,
						getCheckboxProps: record => ({
							props: {
								//已经完成添加的采取禁用处理
								disabled: projectDisabledUserIds.indexOf(record.userId) !== -1,
							}
						}),
						type: 'checkbox'
					}"
						:columns='tableColumns'
						:dataSource='projectTableDataList'
						:rowKey='
						(record, index) => {
							//已经完成添加的采取禁用处理
							return record.userId;
						}
					'
						:pagination='projectPagination'
						@change='projectHandleTableChange'
					></a-table>
				</a-card>
			</a-tab-pane>
			<a-tab-pane :key="'2'" :tab="$t('plan.team-members.dfmea-all')">
				<a-card class='table-wrapper'>
					<a-table
						:rowSelection="{
						selectedRowKeys: selectedRowKeys,
						onChange: onAddSelectChange,
						getCheckboxProps: record => ({
							props: {
								disabled: disabledUserIds.indexOf(record.userId) !== -1,
							}
						}),
						type: 'checkbox'
					}"
						:columns='tableColumns'
						:dataSource='tableData'
						:rowKey='
						(record, index) => {
							return record.userId;
						}
					'
						:pagination='pagination'
						@change='handleTableChange'
					></a-table>
				</a-card>
			</a-tab-pane>
		</a-tabs>
	</a-modal>
</template>
<script>

const checked = new Set();
export default {
	props: {
		showAddModal: {
			type: Boolean,
			default: false
		},
		// 核心成员数据
		teamTableData: {
			type: Array,
			required: true,
		},
		// 项目成员数据
		projectTableData: {
			type: Array,
			required: true,
		},
		//是否核心标识
		coreFlag: {
			type: Boolean,
			default: false
		},
		fmeaId:{
			type:Number ,
			required: false,
			default: undefined
		}
	},
	watch: {
		showAddModal(val) {
			if (val) {
				this.tabKey = '1';
				let team = [];
				if (this.teamTableData)this.teamTableData.forEach(item => {
					if (item.userDepartmentId){
						team.push(item.userDepartmentId)
					}else {
						team.push(item.userId);
					}

				});
				let userInfo = JSON.parse(localStorage.getItem('userInfo'));
				this.selectedRowKeys = team;
				this.projectSelectedRowKeys = team;
				this.initDisabledUserIds = team;
				this.projectDisabledUserIds = team;
				this.initDisabledUserIds.push(userInfo.userId);
				this.projectDisabledUserIds.push(userInfo.userId);
				this.getMyProjectUserPageList();
				this.getUserPageList();
			}
		},

	},
	data() {
		return {
			tabKey: '1',
			key: 0,
      // 选中行
			selectedRowKeys: [],
			projectSelectedRowKeys: [],
      // 禁用用户
			initDisabledUserIds: [],
      // 全部成员禁用用户
			disabledUserIds: [],
      // 项目成员禁用用户
			projectDisabledUserIds: [],
      // 表格数据
			tableData: [],
      // 项目成员数组
			newMemberArray: [],
      // 全部成员数组
			newArray: [],
			// 人员添加--表头
			tableColumns: [
				{
					title: this.$t('plan.team-members.name'),
					align: 'center',
					dataIndex: 'userName',
					ellipsis: true
				},
				{
					title: this.$t('plan.team-members.account'),
					align: 'center',
					dataIndex: 'account',
					ellipsis: true
				},
				{
					title: this.$t('plan.citation-family-dfmea.department'),
					align: 'center',
					dataIndex: 'departmentName',
					ellipsis: true
				}
			],
			// 分页
			pagination: {
				current: 1,
				pageNo: 1,
				pageSize: 6, // 默认每页显示数量
				showTotal: total => this.$t('plan.team-members.workbench.a-total-of-data', {total: `${total}`}), // 显示总数
				total: 0, //总条数
				showQuickJumper: true
			},
			projectPagination: {
				current: 1,
				// defaultPageSize: 10,
				pageNo: 1,
				pageSize: 6, // 默认每页显示数量
				showTotal: total => this.$t('plan.team-members.workbench.a-total-of-data', {total: `${total}`}), // 显示总数
				total: 0, //总条数
				showQuickJumper: true
			},
			form: {
				userName: undefined
			},
			projectTableDataList:[],
			tempArray : new Map,
			tempProjectArray : new Map,
			lastRowKeys:undefined,
			lastProjectRowKeys:undefined,
		}
	},

	methods: {
    // 添加团队成员 change
		onAddSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys;
			//项目成员和全部成员 勾选一致
			//记录上一份数据
			this.lastRowKeys= selectedRowKeys;
			//设置 勾选的同步
			this.projectSelectedRowKeys = this.lastRowKeys ? [...new Set(this.lastRowKeys.concat(this.selectedRowKeys))]: [...new Set(this.selectedRowKeys.concat(this.lastRowKeys))];
			// 已勾选表格团队成员
			let teamTableUserIds = [];
			// 团队成员标识
      teamTableUserIds = (this.teamTableData || []).map((item) => {
        return item.userId;
      });
			// 已添加到表格团队成员，差集
			let diffArr = this.selectedRowKeys.concat(teamTableUserIds).filter(e =>
				this.selectedRowKeys.includes(e) && !teamTableUserIds.includes(e));
			// 根据用户ID，set用户信息到新数组
			if (diffArr && diffArr.length > 0) {
				this.newArray = [];
				//保存不同页面 已勾选的数据
				if (this.tempArray){
					//获取 key的迭代对象
					let iterableIterator = this.tempArray.keys();
					loop :while (true){
						//获取当前 key值
						let next = iterableIterator.next().value;
						if (!next){
							break loop;
						}
						//不为当前页面的勾选数据时 合并数据
						if (next != this.pagination.pageNo){
							selectedRows =selectedRows.concat(this.tempArray.get(next))
						}
					}

				}
				for (let i = 0; i < selectedRows.length; i++) {
					let item = selectedRows[i];
					if (diffArr.indexOf(item.userId) !== -1) {
						this.newArray.push(item);
					}
				}
				//设置 或者 更新 当前页面的勾选数据
				this.tempArray.set(this.pagination.pageNo,selectedRows);
			} else {
				this.newArray = [];
			}
		},
    // 添加项目成员作为团队成员 change
		onMemberAddSelectChange(projectSelectedRowKeys, projectSelectedRows) {
			this.projectSelectedRowKeys = projectSelectedRowKeys;
			//项目成员和全部成员 勾选一致
			//记录上一份数据
			this.lastProjectRowKeys= projectSelectedRowKeys;
			//设置 勾选的同步
			this.selectedRowKeys = this.lastProjectRowKeys ? [...new Set(this.lastProjectRowKeys.concat(this.projectSelectedRowKeys))]: [...new Set(this.projectSelectedRowKeys.concat(this.lastProjectRowKeys))];
			// 已勾选表格团队成员
			let teamTableUserIds = [];
      teamTableUserIds = (this.teamTableData || []).map((item) => {
        return item.userId
      });
			// 已添加到表格团队成员，差集
			let diffArr = this.projectSelectedRowKeys.concat(teamTableUserIds).filter(e =>
				this.projectSelectedRowKeys.includes(e) && !teamTableUserIds.includes(e));
			// 根据用户ID，set用户信息到新数组
			if (diffArr && diffArr.length > 0) {
				this.newMemberArray = [];
				//保存不同页面 已勾选的数据
				if (this.tempProjectArray){
					//获取 key的迭代对象
					let iterableIterator = this.tempProjectArray.keys();
					loop :while (true){
						//获取当前 key值
						let next = iterableIterator.next().value;
						if (!next){
							break loop;
						}
						//不为当前页面的勾选数据时 合并数据
						if (next != this.projectPagination.pageNo){
							projectSelectedRows =projectSelectedRows.concat(this.tempProjectArray.get(next))
						}
					}

				}
				for (let i = 0; i < projectSelectedRows.length; i++) {
					let item = projectSelectedRows[i];
					if (diffArr.indexOf(item.userId) !== -1) {
						this.newMemberArray.push(item);
					}
				}
				//设置 或者 更新 当前页面的勾选数据
				this.tempArray.set(this.projectPagination.pageNo,projectSelectedRows);
			} else {
				this.newMemberArray = [];
			}
		},
		// 弹窗--点击分页中数字触发的方法(全部)
		handleTableChange(pagination) {
			this.pagination.pageSize = pagination.pageSize;
			this.pagination.current = pagination.current;
			this.pagination.pageNo = pagination.current;
			this.getUserPageList();
		},
    // 弹窗--点击分页中数字触发的方法(项目成员)
		projectHandleTableChange(projectPagination) {
			this.projectPagination.pageSize = projectPagination.pageSize;
			this.projectPagination.current = projectPagination.current;
			this.projectPagination.pageNo = projectPagination.current;
			this.getMyProjectUserPageList();
		},
		// 弹窗--列表渲染（全部）
		async getUserPageList() {
			let data = {
				pageNo: this.pagination.current,
				pageSize: this.pagination.pageSize,
				userName: this.form.userName,
				fmeaFrom: 'mfmea'
			};
      await this.$api.getUserListForFmeaPermission(data).then(res => {
        if (!res.flag) {
          this.$notification.error({message: res.message});
        }
        if (res.data.data)res.data.data.forEach(item => {
          item.index = this.key;
          this.key++;
        });
        this.$nextTick(() => {
          this.tableData = res.data.data || [];
          this.pagination.total = res.data.total || 0;
          // 筛选无角色用户不可选择
          this.disabledUserIds = [];
          this.tableData.forEach((data)=>{
            if (!data.role) {
              this.disabledUserIds.push(data.userId);
            }
          })
          this.disabledUserIds = [...this.disabledUserIds, ...this.initDisabledUserIds];
        });
      });
		},
    // 切换Tab
		callback(key) {
			this.tabKey = key;
		},
    // 确认添加团队成员
		async handleAddSubmit() {
			let team = this.teamTableData;
			let userInfo = JSON.parse(localStorage.getItem('userInfo'));
      let userId = userInfo.userId;
			if (this.newArray || this.newMemberArray) {
        // 整理待添加的成员数组 除去FMEA的Owner
				let arr1 = this.newArray.filter(item => item.userId !== userId);
				let arr2 = this.newMemberArray.filter(item => item.userId !== userId);
				let arr = arr1.concat(arr2).filter(item => team.findIndex(it => it.userId === item.userId) < 0);
				let param = [];
				//数据去重
				await arr.forEach((itemA) => {
					let check = param.every((itemB) =>{
						return itemA.userId !== itemB.userId;
					})
					check ? param.push(itemA): "";
				})
        // 根据成员的角色ID整理待添加成员集合
        let addUserList = [];
        if (param && param.length > 0) {
          for (let i = 0; i < param.length; i++) {
            let ordinal = i + 1;
            let user = param[i];
            let obj = {
              departmentId: user.departmentId,
              userId: user.userId,
              orgId: user.orgId,
              userName: user.userName,
              type: 'add',
              departmentName: user.departmentName,
              userDepartmentId: user.userId + '/' + user.departmentId,
              ordinal: ordinal,
              mobile: user.mobile,
              email: user.email,
              teamType: 1, // 默认为核心团队
              purview: 1 // 默认为编辑权限
            }
            addUserList.push(obj);
          }
        }
        let data = {
          fmeaId: this.fmeaId,
          rfmeaId: this.$store.getters.rfmeaId,
          addTeamMemberList: addUserList,
          modifyTeamMemberList: []
        }
        this.$api.addTeamMember(data).then(res => {
          if (res.flag) {
            this.$notification.success({ message: res.message });
          }
        }).finally(() => {
          this.selectedRowKeys = [];
          this.projectSelectedRowKeys = [];
          this.tempArray= new Map;
          this.tempProjectArray = new Map;
          this.newArray = [];
          this.newMemberArray = [];
          this.form.userName = undefined;
          this.form.departmentName = undefined;
          this.projectPagination.current = 1;
          this.projectPagination.pageNo = 1;
          this.pagination.current = 1;
          this.pagination.pageNo = 1;
          this.$emit('handleAddSubmit');
        });
			}

		},
		// 弹窗 -- 取消
		handleCancel() {
			this.form.userName = undefined;
			this.selectedRowKeys = [];
			this.form.departmentName = undefined;
			this.tempArray= new Map;
			this.tempProjectArray = new Map;
			this.newMemberArray = [];
			this.$emit('cancel');
		},
    // 弹窗 -- 重置
		reset() {
			this.form.userName = undefined;
			this.form.departmentName = undefined;
      this.projectPagination.current = 1;
			this.pagination.current = 1;
			this.getMyProjectUserPageList();
			this.getUserPageList();
		},
		// 弹窗 -- 查询
		search() {
      this.projectPagination.current = 1;
			this.pagination.current = 1;
			switch (this.tabKey) {
				case '1':
					this.getMyProjectUserPageList();
					break;
				case '2':
					this.getUserPageList();
					break;
				default:
					break;
			}
		},
		//获取项目成员
		getMyProjectUserPageList() {
			let data = {
				pageNo: this.projectPagination.current,
				pageSize: this.projectPagination.pageSize,
				userName: this.form.userName,
				fmeaId: this.fmeaId,
				flag: false,
				fmeaFrom: 'mfmea'
			};
			this.$api.getMyProjectUserPageList(data).then(res => {
				if (res.flag) {
					this.projectTableDataList = res.data.data || [];
					if (res.data.data)res.data.data.forEach(item => {
						item.index = this.key;
						this.key++;
					});
					this.projectPagination.total = res.data.total || 0;
				} else {
					this.projectTableDataList = [];
				}
			});
		},
	},
	mounted() {
	}
}
</script>
