<template>
	<div>
		<div flex style="height: 100%;">
			<base-layout :buttonShow="false" style="width: 260px;font-size: 13px;" :isPage="false"
				:buttonList="buttonTreeList" @onFuncBtn="handleTreeThings" :showTitle="false" :defaultButtonSwitch="false">
				<div slot="main" style="height: 100% ;overflow-y: auto;border-right: 1px solid #dfe6ec;">
					<base-tree :isCenter="false" :isSaveBtn="false" :Allshow="false" :showCheckbox="false"
						:menuData="menuData" @handleNodeClick="orangClick"></base-tree>
				</div>
			</base-layout>
			<base-layout :buttonList="buttonList" :isPage="true" :showTitle="false" @onFuncBtn="handleDialog"
				ref="userTablePage" style="flex:1;" @pageChange="onPageChange">


				<div slot="main" slot-scope="{ tableHeight }" style="height: 100%;">
					<base-table :border="true" :showIndex="false" :slotrow="true" :tableHeight="tableHeight"
						:funData="funData" :tabLoading.sync="tabLoading" :tableData="tableData" :tableColumn="tableColumn"
						@onFunc="onFunc" @radioChange="radioChange" ref="userTableData">
						<template v-slot:option="{ row }">
							<el-radio v-model="radioModel" :label="row.$index">
								<span></span>
							</el-radio>
						</template>
						<template v-slot:companyCount="{ row }">
							<span @click="handleclickOpenChecklist(row.row)"
								style="width:100%;cursor: pointer;color:#3ca2e1">{{
									row.row.companyCount
								}}</span>
						</template>
					</base-table>
				</div>
			</base-layout>
		</div>
		<!-- S 新增弹窗 -->
		<base-dialog :dialogVisible.sync="fileManagementDialog" :closeModal="false" :footerShow="true" :title="dialogType"
			width="95%" top="3vh" @handleConfirmClick="handleAddDialogDetails">
			<base-form :formRow="plusDialogListRow" :isFunBtn="isFunBtn" ref="custmanForm" @onSelect="onSelect"
				:rules="rules" :spanNumber="8" @elDialogClick="elDialogClick"></base-form>
			<user-details ref="custmanUserDetails"></user-details>
			<attachment-details ref="custmanAtt"></attachment-details>
		</base-dialog>
		<!-- E 新增弹窗 -->

		<!-- S 分管部门 -->
		<base-organization ref="baseOrganization" :menuData="OrganTreeData"
			@handleConfirmClick="handleOrganTreeDetails"></base-organization>

		<!-- S 组织机构树弹窗 -->
		<base-dialog :dialogVisible.sync="treeManagementDialog" :closeModal="false" :footerShow="true"
			:title="treeDialogType" width="55%" top="20vh" @handleConfirmClick="handleTreeDialogDetails">
			<base-form :formRow="treeDialogListRow" :isFunBtn="isFunBtn" ref="treeDataRef"
				:rules="rulesTreeDialog"></base-form>
		</base-dialog>
		<!-- E 组织机构树弹窗 -->

		<!-- S 查看 -->
		<base-dialog :dialogVisible.sync="showManagementDialog" :closeModal="false" :footerShow="true" title="查看"
			width="75%" top="3vh" @handleConfirmClick="handleShowDialogDetails">
			<look-form :formRow="showFormColumn" :spanNumber="spanNumber" :ruleForm="showFormData"></look-form>

			<base-table :border="true" :showIndex="false" :tabLoading.sync="tabLoading" :slotrow="false"
				:tableData="detailedTableData" :tableColumn="detailedTableColumn">
				<!--  序号  -->
				<template v-slot:index="{ row }">
					<span>{{ row.index + 1 }}</span>
				</template>
				<template v-slot:isdefault="{ row }">
					<span>{{ row.isdefault == 1 ? "是" : "否" }}</span>
				</template>
			</base-table>

			<base-table :border="true" :showIndex="false" :tabLoading.sync="tabLoading" :slotrow="false"
				:tableData="enclosureTableData" :tableColumn="enclosureTableColumn">
				<!--  序号  -->
				<template v-slot:index="{ row }">
					<span>{{ row.index + 1 }}</span>
				</template>
				<template v-slot:sa_UploadDateTime="{ row }">{{ formatTime(row.sa_UploadDateTime) }}
				</template>

			</base-table>
		</base-dialog>
		<!-- E 查看 -->

		<!-- S 选择所属公司弹窗 -->
		<base-dialog :dialogVisible.sync="showOperateDialog" :closeModal="false" :footerShow="true" title="选择所属公司"
			width="45%" height="75vh" top="20vh" @handleConfirmClick="handleOperateDialogDetails">
			<el-checkbox-group v-model="checkList" style="display: flex;flex-wrap: wrap;">
				<el-checkbox v-for="(item, index) in labelList" :key="index" style="width: 28%;padding: 10px;" :label="item.companyName
					" :checked="item.checked"></el-checkbox>
			</el-checkbox-group>
		</base-dialog>
		<!-- E 选择所属公司弹窗 -->

		<!-- S 所属公司查看弹窗 -->
		<base-dialog :dialogVisible.sync="showCompanyDialog" :closeModal="false" :footerShow="false" title="所属公司"
			height="75vh" width="15%" top="20vh">
			<div class="company-list" v-for="(item, index) in openList" :key="index">{{ item.companyName }}</div>
		</base-dialog>
		<!-- E 所属公司查看弹窗 -->


	</div>
</template>
<script>
// 组件
import baseLayout from '@/components/base/baseLayout'
import baseTable from '@/components/base/baseTable'
import baseDialog from '@/components/base/BaseNewDialog'
import baseForm from '@/components/base/baseNewForm'
import baseCheck from '@/components/base/baseCheck'
import baseTree from '@/components/base/BaseMenuTree'
import lookForm from '@/components/base/baselookForm/index.vue'
import {
	getCompanyId
} from '@/utils/auth'
import baseOrganization from "@/components/base/baseOrganization/index.vue";
// 表头数据
import configData from './configData.js'
// 表格数据
import {
	getUserTableList, getUserMenuList, GetListByparentID,
	customerSaveData, GetOrganTree, GetBillData,
	DelData,
	classifySaveCusData,
	classifyDelCusData,
	GetCusEditList,
	SaveVenDate, GetDistribute
} from '@/api/apis/fileManagement'
import userDetails from './userDetails.vue'
import attachmentDetails from './attachmentDetails.vue'
import {
	OrganGetCompany
} from '@/api/apis/organization'
import { UploadList, } from "@/api/apis/auth.js";

export default {
	name: 'userManagement',
	components: {
		baseLayout,
		baseTable,
		baseDialog,
		baseForm,
		baseTree,
		userDetails,
		attachmentDetails,
		lookForm,
		baseOrganization, baseCheck
	},
	data() {
		return {
			mainColor: '#f8f8f8',
			menuData: [], //菜单树数据
			funData: [{
				color: '#3CA2E1',
				text: '选择所属公司'
			},
			],
			buttonList: [
				{
					icon: 'el-icon-reading',
					menuName: '查看',
				},
			], //表格按钮组
			buttonTreeList: [{
				icon: 'el-icon-plus',
			},
			{
				icon: 'el-icon-edit',
			},
			{
				icon: 'el-icon-delete',
				type: 'danger',
			},
			], //树
			rulesTreeDialog: configData.rulesTreeDialog,
			treeManagementDialog: false,
			treeDialogType: '新增',

			showOperateDialog: false,//操作弹窗
			showCompanyDialog: false,//所属公司查看弹窗
			tabLoading: false,

			// tableHeight: '67vh',
			tableData: [], //表格数据
			dialogType: '新增', //表格类型
			fileManagementDialog: false, //控制新增编辑弹窗是否打开
			Ddk_DataDicKindID: '', //组织
			selectTableData: [], //当前选中的数据
			plusDialogListRow: configData.plusDialogList, //新增表单
			isFunBtn: false,
			radioModel: false, //单选
			treeNodeSelected: {
				//当前选中的树节点
				cusClassify: '',
				cusClassifyName: '',
			},
			rules: configData.rules,
			OrganTreeDialogVisible: false, //分管部门弹窗
			OrganTreeData: [], //分管部门
			treeHeight: '100%',
			organizationForm: {}, //选择组织机构
			selectTableData: {}, //当前选中的数据
			showManagementDialog: false, //查看
			showFormColumn: configData.showFormColumn,
			spanNumber: 8,
			showFormData: {},
			detailedTableColumn: configData.plusTableColumn,
			detailedTableData: [],
			enclosureTableColumn: configData.enclosureTableColumn,
			enclosureTableData: [],
			pageModel: { //分页
				limit: 20,
				page: 1
			},
			labelList: [],//
			checkList: [],
			openList: [],
			appendix: [],
		}
	},
	computed: {
		//用户档案表头数据
		tableColumn() {
			return configData.userTableColumn
		},
		treeDialogListRow() {
			return configData.treeFormData
		},
	},
	mounted() {
		// 初始化
		this.initPage()
	},
	methods: {
		formatTime(row) {
			return row && row.substring(0, 10);
		},
		initPage() {
			this.CreatePersonID = this.$store.state.user.info.UserID
			this.getMenuList()
			this.getTableData()
			this.getListByparent()
			this.getCompanyList()
		},
		async handleclickOpenChecklist(row) {
			if (row.companyCount > 0) {
				this.getCheckListData(row)
				this.showCompanyDialog = true
			} else {
				this.getCheckListData(row)
			}
		},
		//操作
		onFunc(index, row) {
			// console.log(row);
			if (row.companyCount > 0) {
				this.getCheckListData(row)
			} else {
				this.checkList = []
			}
			this.showOperateDialog = true
		},
		// 客户档案表格数据
		async getTableData() {
			this.tabLoading = true
			setTimeout(() => {
				this.tabLoading = false
			}, 5000)
			let params = {
				...this.pageModel,
				cusClassify: this.treeNodeSelected.cusClassify, //当前点击分类id
				Sequence: '',
				SequenceName: '',
			}
			let res = await getUserTableList(params)
			if (res.code == 1) {
				this.$nextTick(() => {
					this.tableData = res.data[1]
					this.$refs.userTableData.clearRadioIndex()
					this.selectTableData = {}
					this.$refs.userTablePage.setPageTotal(res.data[0])
				})
				this.tabLoading = false
			}
		},
		// 分页
		onPageChange(model) {
			this.pageModel.page = model.page;
			this.pageModel.limit = model.limit
			this.getTableData()
		},
		// 客户档案s树组织列表
		async getMenuList() {
			let res = await getUserMenuList({})
			// 请求数据成功
			if (res.code === 1) {
				this.menuData = res.data[0]
				// console.log(this.menuData, "menuData")
			}
		},
		// 行单击
		radioChange(val) {
			this.selectTableData = val
			this.radioModel = val.index
		},

		// 树节点被点击
		orangClick(data) {
			this.treeNodeSelected.cusClassifyName = data.label
			this.treeNodeSelected.cusClassify = data.id
			this.getTableData()
		},
		// 监听分管部门输入框
		elDialogClick(row, index, indexRow) {
			if (row.prop === 'orgainName') {
				this.$refs.baseOrganization.dialogVisible = true
				this.getOrganTreeList()
			}
		},
		//选择器选中
		onSelect(val, index, indexRow) {
			if (indexRow == 0) {
				//省
				this.plusDialogListRow[3].elCol[1].options = []
				this.plusDialogListRow[3].elCol[2].options = []
				this.$refs.custmanForm.ruleForm.city = ''
				this.$refs.custmanForm.ruleForm.county = ''
			}
			if (indexRow == 1) {
				//市
				this.plusDialogListRow[3].elCol[2].options = []
				this.$refs.custmanForm.ruleForm.county = ''
			}
			this.getListByparent(val, indexRow)
		},
		// 省、市、县下拉框数据
		async getListByparent(id, indexRow) {
			let params = {
				id: id ? id : '-1',
			}
			let res = await GetListByparentID(params)
			if (res.code === 1) {
				if (!id) {
					//省
					// console.log(res.data)
					this.plusDialogListRow[3].elCol[0].options = res.data[0]
				} else {
					if (indexRow == 0) {
						//市
						this.plusDialogListRow[3].elCol[1].options = res.data[0]
					} //县
					if (indexRow == 1) {
						this.plusDialogListRow[3].elCol[2].options = res.data[0]
					}
				}
			}
		},
		// 获取附件列表
		async UploadList1(item) {
			if (JSON.stringify(item) != '[]') {
				let list = item.split("'")
				this.appendix = []
				list.forEach(el => {
					if (el != "" && el != ', ') {
						this.appendix.push(el)
					}
				});
				const res = await UploadList({
					page: "1", //当前页码
					limit: "10", //每页显示多少
					billid: "", //业务单据ID
					filesIDs: this.appendix, //附件ID
				})
				if (res.success == "true") {
					this.enclosureTableData = res.data[1]
				}
			}
		},
		// 弹窗-分管部门组织机构树
		async getOrganTreeList() {
			let params = {
				// CompanyID: '1',
				CompanyID: this.$store.state.user.companyID ? this.$store.state.user.companyID : getCompanyId()
			}
			let res = await GetOrganTree(params)
			if (res.code == 1) {
				this.OrganTreeData = JSON.parse(res.data[0])
			}
		},
		// 获取公司列表
		async getCompanyList() {
			let res = await OrganGetCompany({})
			if (res.code == 1) {
				this.labelList = res.data[0]
				// console.log(this.labelList);
			}
		},
		//查询已分配公司列表
		async getCheckListData(row) {
			let params = {
				baseKind: row.cusClassify, //客户种类
				baseID: row.billid //
			}
			let res = await GetDistribute(params)
			if (res.code == 1) {
				this.openList = res.data[0]
				this.checkList = this.openList.map(item => item.companyName)
			}
		},
		//选择所属公司弹窗确认
		async handleOperateDialogDetails() {
			//过滤并组成新数组
			const checkListId = this.labelList.filter(item => this.checkList.includes(item.companyName)).map(item => item.companyID);
			let params = {
				baseKind: this.selectTableData.cusClassify,//客户分类id
				baseID: this.selectTableData.billid, //唯一billid
				companyID: checkListId
			}
			let res = await SaveVenDate(params)
			if (res.code === 1) {
				this.$vmNews('分配所属成功', 'success')
				this.showOperateDialog = false
				this.checkLis = []
				this.getTableData()
			}
		},
		// 分管部门确定按钮
		handleOrganTreeDetails(val) {
			this.$refs.custmanForm.getField("orgainName", val.label);
			this.$refs.custmanForm.getField("organID", val.id);
			this.$refs.baseOrganization.dialogVisible = false
			// console.log(this.$refs.custmanForm.ruleForm);

		},
		// 获取当前行详情数据
		async getrowDetails(val) {
			let params = {
				id: val.billid,
				op: "",
			};
			let res = await GetBillData(params)
			if (res.code === 1) {
				let data = res.data
				// console.log(data);
				this.$nextTick(() => {
					if (data[0].province != '' && data[0].province != null) {
						data[0].province = parseInt(data[0].province)
					}
					if (data[0].city != '' && data[0].city != null) {
						data[0].city = parseInt(data[0].city)
					}
					if (data[0].county != '' && data[0].county != null) {
						data[0].county = parseInt(data[0].county)
					}

					if (this.fileManagementDialog === true) {
						// 编辑
						this.getListByparent(data[0].province, 0)
						this.getListByparent(data[0].city, 1)
						// 表单数据回滚
						this.$refs.custmanForm.incomingParameters(data[0])
						this.$refs.custmanUserDetails.tableData = data[1]
						this.$refs.custmanAtt.$refs.uploadAttachments.UploadList1(data[2])
					}
					// 查看
					if (this.showManagementDialog === true) {
						this.showFormData = data[0]
						this.detailedTableData = data[1]
						this.UploadList1(data[2])

					}
				})
			}
		},

		handleDialog(item) {
			// 新增
			if (item.menuName === '新增') {
				this.dialogType = '新增'
				if (this.treeNodeSelected.cusClassify === '') {
					this.$vmNews('请选择分类', 'warning')
					return
				} else {
					this.fileManagementDialog = true
					this.$nextTick(() => {
						this.$refs.custmanForm.incomingParameters(this.treeNodeSelected)
					})
				}
			}
			// 编辑
			if (item.menuName === '编辑') {
				this.dialogType = '编辑'
				if (Object.keys(this.selectTableData).length === 0) {
					this.$vmNews('请选择一条数据!', 'warning')
					return
				} else {
					this.fileManagementDialog = true
					this.$nextTick(() => {
						// let billid = this.selectTableData.billid
						let val = this.selectTableData;
						this.getrowDetails(val)
					})
				}
			}
			// 删除
			if (item.menuName == '删除') {
				if (Object.keys(this.selectTableData).length === 0) {
					this.$vmNews('请选择一条数据!', 'warning')
					return
				} else {
					this.$delConfirm().then(() => {
						let billid = this.selectTableData.billid
						this.removeTableItem(billid)
					})
				}
			}
			// 查看
			if (item.menuName == '查看') {
				if (Object.keys(this.selectTableData).length === 0) {
					this.$vmNews('请选择一条数据!', 'warning')
					return
				} else {
					this.showManagementDialog = true
					let val = this.selectTableData;
					this.getrowDetails(val)
				}
			}
		},
		// 保存
		handleAddDialogDetails() {
			this.$refs.custmanForm.$refs['ruleForm'].validate((valid) => {
				if (valid) { this.saveAddDialogDetails() } else {
					this.$message({ message: '请输入必填项', type: 'warning' }); return
				}
			})
		},
		async saveAddDialogDetails() {
			let params = {
				dataMain: {
					billid: this.dialogType == '新增' ?
						'00000000-0000-0000-0000-000000000000' :
						this.selectTableData.billid,
					...this.$refs.custmanForm.ruleForm,
					CreatePersonID: this.CreatePersonID,
				},
				base_Customer_Linkman: this.$refs.custmanUserDetails.tableData,
				attIDS: this.$refs.custmanAtt.$refs.uploadAttachments.appendix.join(),
			}
			// console.log(params);
			let res = await customerSaveData(params)
			if (res.code === 1) {
				this.$vmNews('保存成功', 'success')
				this.fileManagementDialog = false
				this.getTableData()
			}
		},
		// 删除
		async removeTableItem(billid) {
			let params = {
				id: billid,
			}
			let res = await DelData(params)
			if (res.code === 1) {
				this.$vmNews('删除成功！', 'success')
				this.getTableData()
			}
		},
		// 处理组织机构树事件
		handleTreeThings(item) {
			// 新增
			if (item.icon === 'el-icon-plus') {
				this.treeDialogType = '新增'
				if (this.treeNodeSelected.cusClassify === '') {
					this.$vmNews('请选择分类', 'warning')
					return
				} else {
					this.treeManagementDialog = true
					let param = {
						parentID: this.treeNodeSelected.cusClassify,
						codename: this.treeNodeSelected.cusClassifyName,
					}
					this.$nextTick(() => {
						this.$refs.treeDataRef.incomingParameters(param)
					})
				}
			}
			// 编辑
			if (item.icon === 'el-icon-edit') {
				this.treeDialogType = '编辑'
				if (this.treeNodeSelected.cusClassify === '') {
					this.$vmNews('请选择分类', 'warning')
					return
				} else {
					this.treeManagementDialog = true
					this.$nextTick(() => {
						let id = this.treeNodeSelected.cusClassify
						this.getDetailsTreeNodeData(id)
					})
				}
			}
			// 删除
			if (item.icon === 'el-icon-delete') {
				if (this.treeNodeSelected.cusClassify === '') {
					this.$vmNews('请选择分类', 'warning')
					return
				} else {
					this.$delConfirm().then(() => {
						let id = this.treeNodeSelected.cusClassify
						this.deleteTreeDialogDetails(id)
					})
				}
			}
		},
		// 选中节点的详细信息
		async getDetailsTreeNodeData(id) {
			let param = {
				id: id
			}
			let res = await GetCusEditList(param)
			if (res.code === 1) {
				this.$refs.treeDataRef.incomingParameters(res.data[1])
			}
		},
		// 组织机构树提交保存
		handleTreeDialogDetails() {
			this.$refs.treeDataRef.$refs['ruleForm'].validate((valid) => {
				if (valid) { this.saveTreeDialogDetails() }
			})
		},
		async saveTreeDialogDetails() {
			let params = {
				dataMain: this.$refs.treeDataRef.ruleForm,
			}
			let res = await classifySaveCusData(params)
			if (res.code === 1) {
				this.$vmNews('保存成功', 'success')
				this.treeManagementDialog = false
				this.getMenuList()
				this.treeNodeSelected.cusClassify = ''
				this.treeNodeSelected.cusClassifyName = ''

			}
		},
		// 组织机构树删除
		async deleteTreeDialogDetails(id) {
			let param = {
				id: id,
			}
			let res = await classifyDelCusData(param)
			if (res.code === 1) {
				this.$vmNews('删除成功', 'success')
				this.getMenuList()
				this.treeNodeSelected.cusClassify = ''
				this.treeNodeSelected.cusClassifyName = ''
			}
		},
		//查看弹窗 确认事件
		handleShowDialogDetails() {
			this.showManagementDialog = false
		},
	},
	watch: {
		// 树弹窗
		treeManagementDialog: {

			deep: true,
			handler(newValue, oldValue) {
				if (newValue === false) {
					// 重置表单
					this.$refs.treeDataRef.resetFields('ruleForm')
				}
			}
		},
		// 新增编辑弹窗
		fileManagementDialog: {
			deep: true,
			handler(newValue, oldValue) {
				if (newValue === false) {
					// 重置表单
					this.$refs.custmanForm.resetFields('ruleForm')
					this.$refs.custmanUserDetails.tableData = []
					this.$refs.custmanAtt.$refs.uploadAttachments.tableData = []
					this.$refs.userTablePage.pageClear()
				}
			}
		},

	}
}
</script>

<style lang="scss" scoped>
.organizationBody {
	display: flex;
	justify-content: space-evenly;
	background-color: #f2f3f4;
	padding: 10px;
}

::v-deep .el-form-item__error {
	padding: 0;
	top: 83%
}

.company-list {
	display: flex;
	flex-direction: column;
	padding: 5px;
	align-items: center;
}
</style>>
