<template>
	<div>
		<base-layout ref="layout" @search="search" :querySwitch="searchList.length == 0 ? false : true" :searchList="searchList" :buttonList="nowBtns"  @pageChange="pageChange" :isPage="true"
			:showTitle="false" @onFuncBtn="getFuncBtn" :fixedButton="true" bgColor="#FAFAFA" @onFixedBtn="onFixedBtn">
			<div slot="main" slot-scope="{ tableHeight }" style="height: 100%;">
				<base-table v-loading="loading" ref="customtable" :showIndex="false" :slotrow="true"
					:tabLoading.sync="tabLoading" :tableHeight="tableHeight" :tableData="tableData"
					:tableColumn="tableColumn" @sortChange="sortChange" @radioChange="radioChange"
					@onCellClick="onCellClick" @doubleClick="doubleClick" id="printMe">
					<template v-slot:createDate="{ row }">
						<span>{{ formatTime(row.row.createDate) }}</span>
					</template>
					<template v-slot:billStateName="{ row }">
						<span :style="textColor(row.row.billStateName)">{{row.row.billStateName}}</span>
					</template>
				</base-table>
			</div>
		</base-layout>
		<base-dialog v-loading="screenLoading" :dialogVisible.sync="screen" title="选择个人查看方案" width="70%" :footerShow="true" @handleConfirmClick="determinePersonalPlan"> 
			<div class="screen">
				<div class="left">
					<span class="title">全部字段</span>
					<el-checkbox-group v-model="personalPlan">
  					  <el-checkbox :label="item.label" v-for="(item,index) in allField" :key="index">{{item.label}}</el-checkbox>
  					</el-checkbox-group>
				</div>
				<div class="right">
					<span class="title">显示字段({{personalPlan.length}})</span>
					<base-table :showIndex="true" :tableColumn="option" :tableData="details" :sortableSwitch="true" tableHeight="472px">
              			<template v-slot:align="{ row }">
              			  <el-select v-model="row.align" placeholder="请选择">
              			    <el-option
              			      v-for="item in align"
              			      :key="item.value"
              			      :label="item.label"
              			      :value="item.value"
              			    >
              			    </el-option>
              			  </el-select>
              			</template>
              			<template v-slot:showLength="{ row }">
              			  <el-input v-model="row.showLength" type="number"></el-input>
              			</template>
              			<template v-slot:isCanSort="{ row }">
              			  <el-switch
              			    :inactive-value="false"
              			    :active-value="true"
              			    v-model="row.isCanSort"
              			  ></el-switch>
              			</template>
              			<template v-slot:color="{ row }">
              			  <el-color-picker v-model="row.color"></el-color-picker>
              			</template>
              			<template v-slot:opeare="{ row }">
              			  <i
              			    class="el-icon-delete"
              			    style="color: red"
              			    @click="delTable(row)"
              			  ></i>
              			</template>
					</base-table>
				</div>
			</div>
		</base-dialog>
		<base-search ref="baseSearch" :searchList="moreQueries" @queryData="queryData"></base-search>
		<textarea id="input" style="position: absolute; top: 0; left: 0; opacity: 0; z-index: -10">复制的</textarea>
	</div>
</template>

<script>
import baseLayout from "@/components/base/baseLayout";
import baseSearch from "@/components/base/baseSearch";
import baseTable from "@/components/base/baseTable";
import configData from "./configData";
import baseDialog from "@/components/base/BaseNewDialog/index.vue";
import { GetBillList,DelData } from '@/api/apis/opportunityManagement'
import {
	getContractList,
	OrganDelContract,
	typeOfContract,
} from "@/api/apis/contract";
import {
  BillMachineGetBillQueryPlan,
  GetDataSourcePerson,
  BillMachineGetDataSource,
  BillMachineSaveDataSource
} from "@/api/apis/documentManagement";
import print from "print-js";
import FileSaver from "file-saver";
import XLSX from "xlsx";

export default {
	name: "ListOpportunity",
	components: {
		baseLayout,
		baseTable,
		baseDialog,
		baseSearch
	},
	data() {
		return {
			textarea: '',
			nowBtns: [
				{
					type: "primary",
					menuName: "查询",
					icon: "el-icon-search",
					// function: 'add'
				},
				{
					type: "primary",
					menuName: "审核",
					icon: "el-icon-coordinate",
				},
				{
					type: "primary",
					menuName: "查看",
					icon: "el-icon-view",
				},
			],
			tabLoading: false,
			tableData: [],
			selectTable: [],
			pageModel: {
				page: 1,
				limit: 20,
				Sequence: "",
				SequenceName: "",
				CodeOrName: "",
				ConType: "",
			},
			selected: [], //选中数据,
			billID: "",//单据ID
			billKindID: "",//单据类型ID
			dialogVisible: false,
			visible: false,
			tableColumnList: configData.tableColumnJson,
			// tableColumn: null,
			tableColumn: configData.tableColumnJson,
			loading: false,
			leftButton: [],
			billStateName: '',
			amountTo: [],
			choiceDialog: false,
			queryCriteria: '',
			sequenceModel: {},
			searchList: [],
			condition: {},
			screen: false,
			personalPlan: [],
			allField: null,
			screenLoading: false,
			standard: null,
			sort: true,
			option: configData.option,
			details: [],
      		align: [
      		  { label: "居中", value: "center" },
      		  { label: "左对齐", value: "left" },
      		  { label: "右对齐", value: "right" },
      		],
			moreQueries: [],
			allList: []
		};
	},
	computed: {
		textColor() {
			return (item) => {
				if (item == "审核中") {
					return { 'color': '#048B08' }
				} else if (item == "未提交") {
					return { 'color': '#999999' }
				} else if (item == "终止") {
					return { 'color': '#E40202'}
				} else {
					return { 'color': '#2878ff' }
				}
			}
		}
	},
	watch: {
		personalPlan(newVal, oldVal) {
			let data = []
			if (this.standard) {
				newVal.forEach(el => {
					let item = this.allList.filter(e =>{
						return el == e.columnNameCN
					})
					if (item.length > 0) {
						data.push(item[0])
					}
				})
				this.details = data
			}
		}
	},
	created() {
		this.init();
	},
	mounted() {
		document.addEventListener('click', this.closeMsg);
	},
	methods: {
		init() {
			this.listData()
		},
		// 更多查询
		queryData(item) {
			this.condition = item
			this.$refs.baseSearch.choiceDialog = false
			this.listData()
		},
		// 删除个人单挑查询条件
		delTable(el) {
			this.$delConfirm().then(res => {
				this.personalPlan.splice(this.personalPlan.findIndex(item => item == el.columnNameCN),1)
			})
		},
		// 查询
		search(el){
			this.condition = el
			this.listData()
		},
		// 保存个人查看方案
		async determinePersonalPlan() {
			const res = await BillMachineSaveDataSource({
				type: '1',
				billKindID: '171',
				dataSourceCoulmn: this.details
			})
			if (res.code == 1) {
				this.screen = false
				this.$message({
					message: "保存个人查看方案成功",
					type: "success",
				});
				this.init()
			}
		},
		// 复制功能
		doubleClick(row, column, cell, event) {
			var text = event.target.innerText;
			var input = document.getElementById("input");
			input.value = text; // 修改文本框的内容
			input.select(); // 选中文本
			document.execCommand("copy");
			this.$notify.success({
				title: `${text}`,
				message: `已复制到剪贴板`,
			});
		},
		// 打印
		duplicate() {
			printJS({
				printable: this.tableData,
				properties: [{
					field: "billStateName",
					displayName: "状态"
				},
				{
					field: "billCode",
					displayName: "线索编码"
				},
				{
					field: "createDate",
					displayName: "制单日期"
				},
				{
					field: "customerName",
					displayName: "客户名称"
				},
				{
					field: "clueState",
					displayName: "线索状态"
				},
				{
					field: "clueTheme",
					displayName: "线索主题"
				},
				{
					field: "important",
					displayName: "重要程度"
				},
				{
					field: "mobilePhone",
					displayName: "联系方式"
				},
				],
				type: "json",
			});
		},
		notClick() { },
		handleClose(done) {},
		closeMsg(e) {
			if (this.visible) {
				this.visible = false
			}
		},
		handleConfirmClick() {
			this.pageModel.CodeOrName = this.queryCriteria
			this.listData();
		},
		changingOver(row) {
			this.pageModel.ConType = row.ddd_DicDetailsID;
			this.listData();
		},
		formatTime(row) {
			return row && row.substring(0, 10);
		},
		async typeOfContract() {
			let params = {
			};
			const res = await typeOfContract(params);
			this.leftButton = res.data[0];
			this.amountTo = res.data
		},
		async listData() {
			this.loading = true;
			const res =  await GetBillList({
				...this.pageModel,
				...this.sequenceModel,
				...this.condition
			})
			if (res.success == 'true') {
				this.$refs.layout.setPageTotal(res.data[0]);
				this.tableData = res.data[1]
			}
			if (this.sort) {
				const el = await GetDataSourcePerson({billKindID: '171'})
				if (el.code == 1) {
					this.tableColumn = el.data[1].length == 0 ? el.data[0] : el.data[1]
					this.allField = el.data[0]
					this.tableColumn.forEach(el => {
						el.tooltip = true
						// el.width = el.span
					});
					this.personalPlan = []
					if (el.data[1].length != 0) {
						el.data[1].forEach(el => {
							this.personalPlan.push(el.label)
						})
					} else {
						el.data[0].forEach(el => {
							this.personalPlan.push(el.label)
						})
					}
				}
				const data = await BillMachineGetBillQueryPlan({billKindID: '171'})
				if (data.code == 1) {
					let item = data.data[0].filter(el => {
						return el.isDefault == true
					})
					this.searchList = item
					let listData = data.data[0].filter(el => {
						return el.isDefault !=true
					})
					// this.searchList = listData
					this.moreQueries = listData
				}
				this.$refs.customtable.setTableKey()
				this.sort = true
			}
			this.$refs.customtable.clearRadioIndex()
			this.loading = false;
		},
		// 点击某条数据
		radioChange(val) {
			this.selected = [];
			this.selected.push(val);
		},
		judgeOn(data,Refresh,id) {
			let el = this.$store.state.tagsView.visitedViews.filter(el => {
				return el.path == '/marketing/leadManagement/newLead'
			})
			if (el.length > 0) {
					this.$confirm('当前页面已打开，继续打开页面原页面数据将被清除，是否继续?', '提示', {
					  confirmButtonText: '确定',
					  cancelButtonText: '取消',
					  type: 'warning'
					}).then(() => {
						this.$router.push({
							path: "newOpportunities",
							query: {
								name: data,
								id: id,
								Refresh: Refresh
							}
						});
					}).catch(() => {
					  this.$message({
						type: 'info',
						message: '已取消操作'
					  });          
				})
			} else {
				this.$router.push({
					path: "newOpportunities",
					query: {
						name: data,
						id: id,
						Refresh: Refresh
					}
				});
			}
		},
		// 点击按钮操作
		getFuncBtn(btnEven) {
			if (btnEven.menuName == "新增") {
				this.judgeOn('新增商机',true)
			} else if (btnEven.menuName == "查看") {
				if (this.selected.length == 0) {
					this.$vmNews("请选择一条记录");
					return;
				}
				this.$router.push({
					path: "viewOpportunity",
					query: {
						id: this.selected[0].billid,
						billKindId: this.selected[0].billKindID,
						Refresh: true
					},
				});
			} else if (btnEven.menuName == "删除") {
				if (this.selected.length == 0) {
					this.$vmNews("请选择一条记录");
					return;
				}
				if (this.selected[0].billStateName != "未提交") {
					this.$vmNews("当前单据无法进行删除");
					return;
				}
				this.$confirm("确认删除吗?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning",
				})
					.then(() => {
						this.delData(this.selected[0].billid);
					})
					.catch(() => {
						this.$message({
							type: "info",
							message: "已取消操作",
						});
					});
			} else if (btnEven.menuName == "编辑") {
				if (this.selected.length == 0) {
					this.$vmNews("请选择一条记录");
					return;
				}
				if (this.selected[0].billStateName != "未提交") {
					this.$vmNews("当前单据无法进行编辑");
					return;
				}
				this.judgeOn('编辑商机',true,this.selected[0].billid)
			} else if (btnEven.menuName == "查询") {
				this.$refs.baseSearch.choiceDialog = true
			} else if (btnEven.menuName == "审核") {
				if (this.selected.length == 0 || this.selected[0].billStateName != "审核中") {
					this.$vmNews("请选择一条“审核中”的记录");
					return;
				}
				this.$router.push({
					path: "viewOpportunity",
					query: {
						id: this.selected[0].billid,
						billKindID: this.selected[0].billKindID,
						Refresh: true
					},
				});
			}
		},
		async delData(id) {
			const res = await DelData({
				id
			});
			if (res.success == "true") {
				this.$message({
					message: "删除成功",
					type: "success",
				});
				this.init();
				this.$refs.customtable.clearRadioIndex();
				this.selected = []
				this.radioIndex = false;
			}
		},
		// 分页发生改变
		pageChange(model) {
			this.pageModel.page = model.page;
			this.pageModel.limit = model.limit;
			this.init();
		},
		// 点击合同号码跳转合同查看
		onCellClick(row, column) {
			if (column == "商机编号") {
				this.$router.push({
					path: "viewOpportunity",
					query: {
						id: row.billid,
						billStateName: row.billStateName,
						Refresh: true
					}
				});
			}
		},
		// 固定按钮操作
		async onFixedBtn(item) {
			if (item.title == "筛选") {
				this.screenLoading = true
				const dataList = await BillMachineGetDataSource({billKindID: "171",type: '0'})
				if (dataList.code == 1) {
					this.allList = dataList.data[0]
				}
				const res =  await BillMachineGetDataSource({billKindID: "171",type: '1'})
				if (res.code == 1) {
					this.screenLoading = false
					this.standard = res.data[0]
					this.personalPlan = []
					this.standard.forEach(el => {
						this.personalPlan.push(el.columnNameCN)
					})
				}
				let data = []
				this.personalPlan.forEach(el => {
					let item = this.standard.filter(e =>{
						return el == e.columnNameCN
					})
					data.push(item[0])
				})
				this.details = data
				this.screen = true
			} else if (item.title == "导出") {
				this.exportEvent(`第${this.pageModel.page}页`);
			} else if (item.title == "打印") {
				this.duplicate();
			}
		},
		exportEvent(excelName) {
			let gatherData = {
				raw: true,
			};
			let grid = XLSX.utils.table_to_book(
				document.querySelector("#printMe"),
				gatherData
			);
			let workbook = XLSX.write(grid, {
				bookType: "xlsx",
				bookSST: true,
				type: "array",
			});
			try {
				FileSaver.saveAs(
					new Blob([workbook], {
						type: "application/octet-stream",
					}),
					excelName + ".xlsx"
				);
			} catch (e) {
				if (typeof console !== "undefined") console.log(e, workbook);
			}
			return workbook;
		},
		change(checked, val) {
			if (checked == false) {
				this.tableColumn = this.tableColumn.filter((item) => {
					return item.label != val.srcElement.defaultValue;
				});
			} else if (checked == true) {
				let num = this.tableColumnList.findIndex((item) => {
					return item.label == val.srcElement.defaultValue;
				});
				this.tableColumn.splice(num, 0, this.tableColumnList[num]);
			}
			this.$nextTick(() => {
				this.$refs.customtable.$refs.elTable.doLayout();
			})
		},
		// 表格多选
		getSelect(selectTable) {
			this.selectTable = selectTable;
		},
		// 详情页 type: 1 新增 2编辑
		goInfo(type = 1, id) { },
		getElSelect(event, index, indexItem, param) { },
		sortChange(prop, order) {
			if (order == 'ascending') {
				this.sequenceModel.Sequence = 'asc'
			}
			if (order == 'descending') {
				this.sequenceModel.Sequence = 'desc'
			}
			this.sequenceModel.SequenceName = prop
			if (!order) {
				this.sequenceModel = {}
			}
			this.sort = false
			this.listData();
		},
	},
};
</script>
<style scoped lang="scss">
.screen {
	display: flex;
	.left {
		.title {
			display: block;
			padding: 10px;
			border-bottom: 1px solid #f5f5f5;
		}
		width: 20%;
		border: 1px solid #f5f5f5;
		::v-deep .el-checkbox-group {
			display: flex;
			Flex-direction: column;
			margin: 10px 0 10px 10px;
			max-height: 450px;
			overflow-y: auto;
		}
	}
	.right{
		.title {
			display: block;
			padding: 10px;
			border-bottom: 1px solid #f5f5f5;
		}
		width: 80%;
		.package{
			margin: 10px 0 10px 10px;
			max-height: 450px;
			overflow-y: auto;
			.mainBody {
				margin-bottom: 7px;
			}
		}
	}
}
.auditDialog {

	::v-deep .el-dialog {
		height: 600px;
		min-height: 300px;
		position: fixed;
		margin-right: 0;
		right: 0;
		border-radius: 10px;
		overflow-y: auto;
	}

	::v-deep .el-button--medium {
		width: 48%;
	}

	.auditNote {
		display: flex;
		flex-wrap: wrap;
		place-content: space-around space-between;
		margin-bottom: 10px;
		background: rgba(192, 196, 204, 0.1);
		font-size: 12px;
		height: 60px;
		padding: 0 10px;
		border-radius: 5px;
		align-content: center;
		justify-content: flex-start;
	}

	::v-deep .el-dialog__header {
		padding: 0;
	}

	::v-deep .el-dialog__body {
		padding: 10px 20px;
	}
}

.el-form-item {
	color: red !important;
}

.dressingByScreening {
	::v-deep .el-button--medium {
		padding: 6px 8px;
		font-size: 14px;
		border-radius: 4px;
		position: absolute;
		top: 14px;
		right: 130px;
	}
}

::v-deep .el-tooltip {
	padding: 0 3px;
}

::v-deep .el-checkbox {
	margin-bottom: 2px;
}

::v-deep .el-tooltip {
	font-size: 14px;
}

::v-deep .pushButton {
	position: relative;
	background-color: #fff
}

::v-deep .el-checkbox__input.is-checked+.el-checkbox__label {
	color: #606266
}

.leftDisplay {
	background-color: #fff;
	overflow-x: clip;
	margin-right: 10px
}

/* 设置带边框的checkbox，选中后边框的颜色 */
.myRedCheckBox.is-bordered.is-checked {
	border-color: #FF0000;
}

/* 设置选中后的文字颜色 */
.myRedCheckBox .el-checkbox__input.is-checked+.el-checkbox__label {
	color: #FF0000;
}

/* 设置选中后对勾框的边框和背景颜色 */
.myRedCheckBox .el-checkbox__input.is-checked .el-checkbox__inner,
.myRedCheckBox .el-checkbox__input.is-indeterminate .el-checkbox__inner {
	border-color: #FF0000;
	background-color: #FF0000;
}

/* 设置checkbox获得焦点后，对勾框的边框颜色 */
.myRedCheckBox .el-checkbox__input.is-focus .el-checkbox__inner {
	border-color: #FF0000;
}

/* 设置鼠标经过对勾框，对勾框边框的颜色 */
.myRedCheckBox .el-checkbox__inner:hover {
	border-color: #FF0000;
}
</style>