<template>
	<div class="content-main">
		<el-row class="search-bm-boder">
			<el-button
				type="primary"
				size="small"
				class="iconfont sortbtn"
				@click="handleSort"
				:disabled="isAdd || isEdit != '' || isSort"
				>{{ isSort ? '排序中···' : '排序' }}</el-button
			><el-button
            type="warning"
            size="small"
            @click="msgDialogVisible = true"
            style="position: absolute; top: 3px; right: 10px"
            >排序说明</el-button
          >
		</el-row>
          <el-dialog
            title="排序说明"
            size="small"
            :visible.sync="msgDialogVisible"
            width="40%"
            top="40vh"
            :modal="false"
          >
            <span
              >&emsp;&emsp;点击“排序”按钮，进入排序编辑状态。长按企业名称，上下拖动到对应位置。松开鼠标，全部企业按新顺序调整，按底部“保存”按钮完成排序。</span
            >
          </el-dialog>
		<el-row class="lrkMar">
			<el-form
				:model="formData"
				ref="formData"
				:rules="formData.rules"
				:inline="true"
			>
				<el-table
					:data="formData.tableList"
					v-loading="listLoading"
					stripe
					border
					fit
					highlight-current-row
					style="width: 100%"
					ref="tableRef"
					:empty-text="isSort?'-':'暂无数据'"
        			:span-method="spanMethodOfParent"
				>
					<el-table-column
						align="center"
						label="序号"
						type="index"
						width="70"
						class-name="handle"
					>
						<template slot-scope="scope">
							{{ scope.$index + 1 }}
						</template>
					</el-table-column>

					<el-table-column
						align="center"
						prop="ccqy"
						label="承储企业名称"
						width=""
						class-name="handle"
					>
						<template slot-scope="scope">
							<el-form-item
								v-if="
									isAdd && !scope.row.id
								"
								:rules="formData.rules.ccqybm"
								:prop="'tableList.' + scope.$index + '.ccqybm'"
							>
								<el-select
          						  filterable
          						  collapse-tags
          						  class="inputCompatibleCck"
          						  v-model="scope.row.ccqybm"
          						  placeholder="请选择企业名称"
								  @change="changeHandle($event,scope.row)"
          						>
          						  <el-option
          						    v-for="item in ssyddmOptions"
          						    :key="item.tyshxydm"
          						    :label="item.kdmc"
          						    :value="item.tyshxydm"
          						  ></el-option>
          						</el-select>
							</el-form-item>
							<span v-else>{{ scope.row.ccqy }}</span>
						</template>
					</el-table-column>
					<el-table-column
						label="对应报表"
          				class-name="table_cell"
					>
          				<template slot-scope="scope">
          				    <el-table 
          				        :data="scope.row.detailList" 
          				        :show-header="false"
          				        empty-text=" "
          				        :class="{in_table:true,inner_table:scope.row.detailList.length==1}"
          				        v-if="scope.row.detailList && scope.row.detailList.length>0"
          				    >
          				        <el-table-column label="对应报表" prop="btbblxmc" >
									<template slot-scope="scopeItem">
										<el-form-item
											v-if="
												(isAdd && !scope.row.id) ||
												isEdit == scope.row.id
											"
											:rules="formData.rules.btbblx"
											:prop="'tableList.' + scope.$index + '.detailList[0].btbblx'"
										>
											<el-select
          									  filterable
          									  collapse-tags
          									  class="inputCompatibleCck"
          									  v-model="scopeItem.row.btbblx"
          									  placeholder="请选择对应报表"
											  @change="btbblxHandle($event,scopeItem.row)"
          									>
          									  <el-option
          									    v-for="item in bblxOptions"
          									    :key="item.dictCode"
          									    :label="item.dictName"
          									    :value="item.dictCode"
          									  ></el-option>
          									</el-select>
										</el-form-item>
										<span v-else>{{ scopeItem.row.btbblxmc }}</span>
									</template>
          				        </el-table-column>
          				        <el-table-column label="补贴标准类型" prop="btbzlxmc">
									<template slot-scope="scopeItem">
										<el-form-item
											v-if="
												(isAdd && !scope.row.id) ||
												isEdit == scope.row.id
											"
											:rules="formData.rules.btbzlx"
											:prop="'tableList.' + scope.$index + '.detailList[0].btbzlx'"
										>
											<el-select
          									  filterable
          									  collapse-tags
          									  class="inputCompatibleCck"
          									  v-model="scopeItem.row.btbzlx"
          									  placeholder="请选择补贴标准类型"
											  @change="btbzlxHandle($event,scopeItem.row)"
											  @visible-change="btbzlxVisible($event,scopeItem.row)"
          									>
          									  <el-option
          									    v-for="item in bzlxOptions"
          									    :key="item.dictCode"
          									    :label="item.dictName"
          									    :value="item.dictCode"
          									  ></el-option>
          									</el-select>
										</el-form-item>
										<span v-else>{{ scopeItem.row.btbzlxmc }}</span>
									</template>
          				        </el-table-column>            
          				    </el-table>
          				    <el-table :data="emptyData"
          				        style="width: 100%,height:100%" 
          				        v-else
          				        :show-header="false"
          				        empty-text=""
          				        class="empty_table">
          				      <el-table-column></el-table-column>
          				      <el-table-column></el-table-column>
          				    </el-table>
          				</template> 
					</el-table-column>
					<el-table-column
						align="center"
						label="补贴标准类型"
						width=""
					>
					</el-table-column>

					<el-table-column align="center" label="操作">
						<template slot-scope="scope">
							<div class="btn_control">
								<el-tooltip
									class="item"
									effect="light"
									content="编辑"
									placement="top"
									v-if="
										scope.row.id && isEdit != scope.row.id
									"
								>
									<el-button
										type="primary"
										size="small"
										:disabled="isSort"
										class="operate_edit_btn iconfont iconxiugai1"
										@click="editHandle(scope.row)"
									></el-button>
								</el-tooltip>
								<el-tooltip
									class="item"
									effect="light"
									content="取消"
									placement="top"
									v-if="
										scope.row.id && isEdit == scope.row.id
									"
								>
									<el-button
										type="primary"
										size="small"
										class="operate_show_btn iconfont iconquxiao"
										@click="cancelHandle(scope.row)"
									></el-button>
								</el-tooltip>
								<el-tooltip
									class="item"
									effect="light"
									content="删除"
									placement="top"
									v-if="
										scope.row.id
									"
								>
									<el-button
										type="primary"
										size="small"
										:disabled="isSort"
										class="operate_delete_btn iconfont iconshanchu"
										@click="handleDelete(scope.row)"
									></el-button>
								</el-tooltip>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</el-form>
			<div class="addTable" v-if="!isAdd && !isSort">
				<el-tooltip
					class="item"
					effect="light"
					content="新增"
					placement="top"
				>
					<span
						class="iconfont iconzengjia addTableSpan"
						@click="addTableItem"
					></span>
				</el-tooltip>
			</div>
        		<el-row v-if="!isSort">
        		  <el-pagination
        		    @size-change="handleSizeChange"
        		    @current-change="handleCurrentChange"
        		    :current-page.sync="pageForm.pageNum"
        		    :page-sizes="[5, 10, 20, 30, 40]"
        		    :page-size="pageForm.pageSize"
        		    layout="total, sizes, prev, pager, next, jumper"
        		    :total="pageForm.total"
        		  ></el-pagination>
        		</el-row>
			<div class="saveTable" v-if="isAdd || isEdit != ''">
				<el-button
					type="primary"
					size="small"
					class="iconfont iconbaocun"
					@click="saveTodo"
					>保存</el-button
				>
				<el-button
					type="primary"
					size="small"
					class="iconfont iconfanhui"
					@click="returnList"
					>返回</el-button
				>
			</div>
			<div class="saveTable" v-if="isSort">
				<el-button
					type="primary"
					size="small"
					class="iconfont iconbaocun"
					@click="saveSort"
					>保存</el-button
				>
				<!-- <el-button
					type="primary"
					size="small"
					class="iconfont iconfanhui"
					@click="endSort"
					>返回</el-button
				> -->
			</div>
		</el-row>
	</div>
</template>
<script>
import {
	enterpriseList,
	enterprisePage,
	enterpriseSort,
	selectkdxxList,
	enterpriseSave,
	enterpriseUpdate,
	enterpriseDelete,
	findReport,
	findSubsidy,
} from '@/api/cwbb/index'
import Sortable from 'sortablejs'

export default {
	data() {
		return {
      		pageForm: {
      		  pageNum: 1,
      		  pageSize: 10,
      		  total: 0,
      		},
			tableData: [],
			repeatData: [],
			formData: {
				tableList: [],
				rules: {
					ccqybm: {
						required: true,
						trigger: 'change',
						message: '请选择',
					},
					btbblx: {
						required: true,
						trigger: 'change',
						message: '请选择',
					},
					btbzlx: {
						required: true,
						trigger: 'change',
						message: '请选择',
					},
				},
			},
			isAdd: false,
			listLoading: false,
			pzProps: {
				label: 'dictName',
				value: 'dictCode',
				children: '',
				emitPath: false,
			},
			pzOptions: [],
			isEdit: '',
			isSort: false,
			ssyddmOptions: [],
			bblxOptions: [
        		{
        		  dictCode: "01",
        		  dictName: "调节储备补贴报表",
        		},
        		{
        		  dictCode: "02",
        		  dictName: "储存费补贴报表",
        		},
        		{
        		  dictCode: "03",
        		  dictName: "包干轮换补贴报表",
        		},
        		{
        		  dictCode: "04",
        		  dictName: "出入库补贴报表",
        		},
        		{
        		  dictCode: "05",
        		  dictName: "倒仓补贴报表",
        		},
			],
			bzlxOptions: [],
			emptyData: [],
			msgDialogVisible: false,
			addList: [],
		}
	},
	methods: {
		// 获取列表
		getList() {
			let data = {...this.pageForm,}
			enterprisePage(data)
				.then((res) => {
					this.listLoading = false
					this.formData.tableList = res.data.list
    	  			this.pageForm.total = res.data.total;
				})
				.catch((err) => {
					this.listLoading = false
					this.$message.error('获取数据失败')
				})
		},
		// 排序列表
		getSortList() {
			this.listLoading = true
			enterpriseList()
				.then((res) => {
					this.listLoading = false
					this.formData.tableList = res.data
				})
				.catch((err) => {
					this.listLoading = false
					this.$message.error('获取数据失败')
				})
		},
    	handleSizeChange(val) {
    	  this.pageForm.pageSize = val;
    	  this.getList();
    	},
    	handleCurrentChange(val) {
    	  this.pageForm.pageNum = val;
    	  this.getList();
    	},
		//新增
		addTableItem() {
			this.isAdd = true
			this.tableData = [...this.formData.tableList]
			this.bzlxOptions = []
			this.formData.tableList.push({
				ccqy: '',
				ccqybm: '',
				detailList: [
					{
						btbblx:"",
						btbblxmc:"",
						btbzlx:"",
						btbzlxmc:"",
					}
				]
			})
			enterpriseList()
				.then((res) => {
					this.addList = res.data
				})
				.catch((err) => {
					this.listLoading = false
					this.$message.error('获取数据失败')
				})
		},
		// 编辑
		editHandle(row) {
			this.isEdit = row.id
			this.bzlxOptions = this.bzlxOptionsCopy
			enterpriseList()
				.then((res) => {
					this.addList = res.data
				})
				.catch((err) => {
					this.listLoading = false
					this.$message.error('获取数据失败')
				})
		},
		// 取消编辑
		cancelHandle(row) {
			this.isEdit = ''
			this.getList()
		},
		// 保存
		saveTodo() {
			this.$refs.formData.validate((valid) => {
				if (valid) {
					this.save()
				} else {
					console.log('请先填写必填项')
				}
			})
		},
		save() {
			if (this.isAdd) {
				let data = {
					...this.formData.tableList[this.formData.tableList.length-1],
					sort: this.addList.length,
				}
				// console.log(data,"data");
				let repeatList = []
				let repeatDetail = []
				repeatList = this.addList.filter(item=>{
					return item.ccqybm == data.ccqybm
				})
				if (repeatList.length > 0) {
					repeatDetail = repeatList[0].detailList.filter(item=>{
						return item.btbblx == data.detailList[0].btbblx
					})
				}
				if (repeatDetail.length > 0) {
					this.$message.error('添加报表重复')
				}else{
					if (repeatList.length > 0) {
						console.log(data,"data");
						data.sort = repeatList[0].sort
					}
					enterpriseSave(data)
						.then((res) => {
    	    				if (res.infoCode == 200) {
								this.getList()
								this.$message.success('添加成功')
    	    				}
						})
						.catch((e) => {
							console.log(e)
						})
					this.isAdd = false
					this.isEdit = ''
				}
			}
			if (this.isEdit != "") {
				let editList = this.formData.tableList.find((d) => d.id == this.isEdit);
				// console.log(editList,"data");
				try{
					editList.detailList.forEach(item=>{
						this.repeatData = editList.detailList.filter(subItem=>{
							return subItem.btbblx == item.btbblx
						})
						if (this.repeatData.length > 1) {
							this.$message.error('对应报表重复')
							throw Error()
						}
					})
				}catch(e){
					console.log(e);
				}
				
				if (this.repeatData.length > 1) {
					return;
				}else{
					enterpriseUpdate(editList)
						.then((res) => {
    	    				if (res.infoCode == 200) {
								this.getList()
								this.$message.success('编辑成功')
    	    				}
						})
						.catch((e) => {
							console.log(e)
						})
					this.isAdd = false
					this.isEdit = ''
				}
			}
		},
		// 返回
		returnList() {
			if (this.isEdit == '') {
				let num = this.formData.tableList.length
				this.formData.tableList.splice(num - 1, 1)
				this.isAdd = false
			} else {
				if (this.isAdd) {
					let num = this.formData.tableList.length
					this.formData.tableList.splice(num - 1, 1)
					this.isAdd = false
					this.isEdit = ''
					this.getList()
				} else {
					this.isEdit = ''
					this.getList()
				}
			}
		},
		listDrop() {
			let el = this.$refs.tableRef.$el.querySelector(
				'.el-table__body-wrapper tbody'
			)

			let _this = this
			this.varsortable = Sortable.create(el, {
				animation: 150,
				sort: true,
				handle: '.handle', // 设置可拖拽行的类名(el-table自带的类名)
				forceFallback: true,
				disabled: !_this.isSort,
				onSort({ newIndex, oldIndex }) {
					// let currRow = _this.newIndexList.splice(oldIndex, 1)[0];
					// _this.newIndexList.splice(newIndex, 0, currRow);
					let data = {
						enterpriseCode:
							_this.formData.tableList[oldIndex].ccqybm,
						startIndex: oldIndex + 1,
						endIndex: newIndex + 1,
					}
					enterpriseSort(data).then((res) => {
						_this.listLoading
						_this.formData.tableList = [] // 1.清空
						_this.$nextTick(() => {
							_this.getSortList() // 2.重新赋值
						})
					})
				},
			})
		},
		// 进行排序
		handleSort() {
			this.isSort = true
			this.getSortList()
			this.varsortable && this.varsortable.destroy()
			this.$nextTick(() => {
				this.listDrop()
			})
		},
		saveSort() {
			this.isSort = false
			this.getList()
			this.varsortable && this.varsortable.destroy()
			this.$nextTick(() => {
				this.listDrop()
				// this.getList()
			})
		},
		// endSort() {
		// 	this.isSort = false
		// 	this.varsortable && this.varsortable.destroy()
		// 	this.$nextTick(()=>{
		// 		this.listDrop()
		// 	})
		// },
    	spanMethodOfParent({row, column, rowIndex, columnIndex}) {
    	    // 从父Table的第2列开始，合并之后的2列（包含第2列），将2列合同成一个单元格，容纳子Table
    	    if(columnIndex === 2) {
    	        return [1, 2]
    	    }
    	    // 隐藏父Table中的第3列
    	    if(columnIndex == 3) {
    	        return [0, 0]
    	    }
    	},
		// 获取承储企业列表
    	getInfo() {
    	  selectkdxxList().then((res) => {
    	    if (res.infoCode == 200) {
    	      this.ssyddmOptions = res.data;
    	    }
    	  });
    	},
		// 获取报表类型
    	getReport() {
    	  findReport().then((res) => {
    	    if (res.infoCode == 200) {
    	      this.bblxOptions = res.data;
    	    }
    	  });
    	},
		// 获取补贴类型
    	getSubsidy() {
    	  findSubsidy().then((res) => {
    	    if (res.infoCode == 200) {
    	      this.bzlxOptionsCopy = res.data;
    	    }
    	  });
    	},
		// 承储企业选择
    	changeHandle(val,item) {
			this.ssyddmOptions.forEach(i=>{
				if (i.tyshxydm == val) {
					item.ccqy = i.qymc
				}
				return;
			})
    	},
		// 对应报表选择
    	btbblxHandle(val,item) {
			item.btbzlx = ""
			item.btbzlxmc = ""
			this.bblxOptions.forEach(i=>{
				if (i.dictCode == val) {
					item.btbblxmc = i.dictName
				}
				return;
			})
    	},
		// 补贴标准类型 显示
    	btbzlxVisible(val,row) {
			this.bzlxOptions = []
			if (val) {
				setTimeout(() => {
					this.bzlxOptions = this.bzlxOptionsCopy.filter(item=>{
						return item.dictCode>(row.btbblx-1)*10 && item.dictCode<row.btbblx*10
					})
				}, 100);
			}
    	},
		// 补贴标准类型选择
    	btbzlxHandle(val,item) {
			this.bzlxOptions.forEach(i=>{
				if (i.dictCode == val) {
					item.btbzlxmc = i.dictName
				}
				return;
			})
    	},
		// 删除
		async handleDelete(row) {
    	  await this.$confirm("此操作将永久删除该信息, 是否继续?", "提示", {
    	    confirmButtonText: "确定",
    	    cancelButtonText: "取消",
    	    type: "warning",
    	  });
    	  enterpriseDelete(row.ccqybm).then((res) => {
    	    if (res.infoCode == 200) {
				this.$message.success('删除成功')
				this.getList()
				this.isAdd = false
				this.isEdit = ''
    	    }
    	  });
    	},
	},
	created() {
		this.getList()
		this.getInfo()
		this.getReport()
		this.getSubsidy()
	},
	mounted() {
		this.listDrop()
	},
}
</script>
<style lang="scss" scoped>
.addTable {
	text-align: right;
	margin-right: 22px;
}
.addTableSpan {
	font-size: 24px;
	// font-weight: bold;
	color: #4588db;
	cursor: pointer;
	margin-right: 20px;
}
.saveTable {
	text-align: center;
	padding: 10px 0;
}
/deep/ .btn_control {
	display: flex;
	justify-content: center;
}
.sortbtn {
	margin-bottom: 10px;
	float: left;
}
/deep/ .handle {
	cursor: pointer;
}
/deep/ .el-button.is-disabled {
	background-color: #a0cfff !important;
}
/deep/ .table_cell{
  .cell{
    padding: 0 !important;
    text-align: center;
    .in_table{
      min-width: 242px;
    }
    .inner_table{
      .el-table__row td {
       border-bottom: 0 !important;
      }
    }
    .el-table::after {
     display: none;
    }
    .el-table::before {
     display: none;
    }
  }
}
//确认弹窗样式
/deep/ .el-message-box {
    border: 0px none;
    padding-bottom: 20px;
}

/deep/ .el-message-box__headerbtn {
    top: 9px;
    right: 7px;
}

/deep/ .el-message-box__status.el-icon-warning {
    display: none;
}

/deep/ .el-message-box .el-message-box__content p {
    height: 100px !important;
    line-height: 100px !important;
}

/deep/ .el-message-box__btns {
    text-align: center;
}

</style>