<template>
	<div class="div_main">
		<div v-show="pageType == 'list'">
			<div class="div_search">
				<el-form
					:inline="true"
					:model="formData"
					ref="ref_searchform"
					:label-width="'80px'"
				>
					<div>
						<el-form-item label="所属组织" prop="gridId">
							<!-- <el-select class="item_width_1"
                         v-model="formData.gridId"
                         placeholder="全部"
                         size="small"
                         clearable>
                <el-option v-for="item in gridList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select> -->

							<el-cascader
								class="customer_cascader"
								ref="myCascader"
								v-model="agencyIdArray"
								:options="orgOptions"
								:props="orgOptionProps"
								:show-all-levels="false"
								@change="handleChangeAgency"
							></el-cascader>
						</el-form-item>
						<el-form-item label="上报渠道" prop="sourceType">
							<el-select
								v-model="formData.sourceType"
								placeholder="请选择"
								size="small"
								clearable
								class="item_width_2"
							>
								<el-option
									v-for="item in qudaoArray"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								>
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="事件内容" prop="eventContent">
							<el-input
								v-model="formData.eventContent"
								class="item_width_1"
								size="small"
								clearable
								placeholder="请输入"
							>
							</el-input>
						</el-form-item>
						<el-form-item label="事件类型" prop="firstIdList">
							<el-cascader
								ref="cascaderEvent"
								v-model="eventTypeCheck"
								:options="cateOptions"
								collapse-tags
								:show-all-levels="false"
								:props="{
									multiple: true,
									checkStrictly: false,
									emitPath: false,
									children: 'subCategory',
									label: 'name',
									value: 'id',
								}"
								clearable
								class="item_width_2"
								@change="handleEventType"
							/>
							<!-- <template slot-scope="{ node, data }">
                  <div @click="cascaderClick(node, data)">
                    <span>{{ data.name }}</span>
                  </div>
                </template>
              </el-cascader> -->
						</el-form-item>
						<el-form-item label="报事人" prop="name">
							<el-input
								v-model="formData.name"
								class="item_width_2"
								size="small"
								clearable
								placeholder="请输入"
							>
							</el-input>
						</el-form-item>
						<el-form-item label="手机号" prop="mobile">
							<el-input
								v-model="formData.mobile"
								class="item_width_2"
								size="small"
								clearable
								placeholder="请输入"
							>
							</el-input>
						</el-form-item>
						<el-form-item label="发生时间" prop="startTime">
							<el-date-picker
								v-model="formData.startTime"
								:picker-options="startPickerOptions"
								class="item_width_2"
								size="small"
								type="date"
								value-format="yyyy-MM-dd HH:mm:ss"
								value="yyyy-MM-dd"
								placeholder="开始时间"
							>
							</el-date-picker>
							<span class="data-tag">至</span>
							<el-date-picker
								v-model="formData.endTime"
								:picker-options="endPickerOptions"
								class="item_width_2 data-tag"
								size="small"
								type="date"
								value-format="yyyy-MM-dd HH:mm:ss"
								value="yyyy-MM-dd"
								placeholder="结束时间"
							>
							</el-date-picker>
						</el-form-item>

						<el-form-item label="状态" prop="status">
							<el-select
								class="item_width_2"
								v-model="formData.status"
								placeholder="全部"
								size="small"
								clearable
							>
								<el-option
									v-for="item in statusArray"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								>
								</el-option>
							</el-select>
						</el-form-item>
						<el-button
							style="margin-left: 30px"
							size="small"
							class="diy-button--search"
							@click="handleSearch"
							>查询</el-button
						>
						<el-button
							style="margin-left: 10px"
							size="small"
							class="diy-button--reset"
							@click="resetSearch"
							>重置</el-button
						>
					</div>
				</el-form>
			</div>

			<div class="div_table">
				<div class="div_btn">
					<el-button
						class="diy-button--add"
						size="small"
						@click="handleAdd"
						>新增</el-button
					>

					<el-button
						@click="handleExport"
						class="diy-button--reset"
						size="small"
						>导出</el-button
					>

					<el-button
						@click="handleMarkDiffcult"
						class="diy-button--export"
						size="small"
						>归档</el-button
					>

					<el-button
						@click="handleCancalDiffcult"
						class="diy-button--delete"
						size="small"
						>取消归档</el-button
					>
				</div>

				<el-table
					:data="tableData"
					border
					v-loading="tableLoading"
					:header-cell-style="{
						background: '#2195FE',
						color: '#FFFFFF',
					}"
					class="table"
					style="width: 100%"
					@selection-change="handleSelectionChange"
					:height="maxTableHeight"
				>
					<el-table-column
						label=""
						fixed="left"
						type="selection"
						align="center"
						width="50"
					/>
					<el-table-column
						label="序号"
						fixed="left"
						type="index"
						align="center"
						width="50"
					/>

					<el-table-column
						prop="gridName"
						align="center"
						label="所属网格"
						:show-overflow-tooltip="true"
					>
					</el-table-column>
					<el-table-column
						prop="categoryName"
						label="事件类型"
						min-width="140"
						align="center"
						:show-overflow-tooltip="true"
					/>
					<!-- <template slot-scope="scope">
              {{ scope.row.firstName + '-' + scope.row.secondName }}
            </template>
          </el-table-column> -->
					<el-table-column
						prop="eventContent"
						label="事件内容"
						align="center"
						:show-overflow-tooltip="true"
					>
					</el-table-column>

					<el-table-column
						prop="imageList"
						align="center"
						width="80"
						label="图片"
					>
						<template slot-scope="scope">
							<el-image
								v-if="
									scope.row.imageList &&
									scope.row.imageList.length > 0
								"
								style="width: 40px; height: 40px"
								:src="scope.row.imageList[0]"
								:preview-src-list="scope.row.imageList"
							>
							</el-image>
							<span v-else></span>
						</template>
					</el-table-column>
					<el-table-column
						prop="voiceList"
						align="center"
						width="80"
						label="音频"
					>
						<template slot-scope="scope">
							<img
								@click="
									handleShowVoice(scope.row.voiceList[0].url)
								"
								class="img-voice"
								v-if="
									scope.row.voiceList &&
									scope.row.voiceList.length > 0
								"
								src="@/assets/img/icon-voice.png"
							/>

							<span v-else></span>
						</template>
					</el-table-column>

					<el-table-column
						prop="sourceTypeName"
						align="center"
						width="110"
						label="上报渠道"
						:show-overflow-tooltip="true"
					>
					</el-table-column>

					<el-table-column
						prop="address"
						align="center"
						:show-overflow-tooltip="true"
						label="地址"
					>
					</el-table-column>

					<el-table-column
						prop="name"
						align="center"
						width="100"
						label="报事人"
						:show-overflow-tooltip="true"
					>
					</el-table-column>

					<el-table-column
						prop="mobile"
						align="center"
						width="110"
						label="手机号"
						:show-overflow-tooltip="true"
					>
					</el-table-column>

					<el-table-column
						prop="satisfactionName"
						align="center"
						width="100"
						label="满意度"
						:show-overflow-tooltip="true"
					>
						<!-- <template slot-scope="scope">

            <span v-if="scope.row.satisfactionName">--</span>
          </template> -->
					</el-table-column>

					<el-table-column
						prop="happenTime"
						align="center"
						width="140"
						:show-overflow-tooltip="true"
						label="发生时间"
					>
					</el-table-column>
					<el-table-column
						prop="operationTypeName"
						align="center"
						width="100"
						:show-overflow-tooltip="true"
						label="结点"
					>
					</el-table-column>

					<el-table-column
						prop="status"
						align="center"
						label="状态"
						width="80"
						:show-overflow-tooltip="true"
					>
						<template slot-scope="scope">
							<span v-if="scope.row.status === 'processing'"
								>处理中</span
							>
							<span v-else-if="scope.row.status === 'closed_case'"
								>已完成</span
							>
							<span v-else>--</span>
						</template>
					</el-table-column>
					<el-table-column
						prop="status"
						align="center"
						label="痛点难点"
						width="80"
						:show-overflow-tooltip="true"
					>
						<template slot-scope="scope">
							<span v-if="scope.row.difficultPoint === '1'"
								>是</span
							>
						</template>
					</el-table-column>

					<el-table-column
						fixed="right"
						label="操作"
						align="center"
						width="100"
					>
						<template slot-scope="scope">
							<el-button
								v-if="
									scope.row.status === 'processing' &&
									!scope.row.operationId
								"
								@click="handleDispose(scope.row)"
								type="text"
								size="small"
								class="div-table-button--edit"
								>处理</el-button
							>

							<el-button
								v-else-if="
									scope.row.status === 'closed_case' &&
									!scope.row.satisfactionName &&
									user.id === scope.row.createdUserId
								"
								@click="handleWatch(scope.row)"
								type="text"
								size="small"
								class="div-table-button--edit"
								>去评价</el-button
							>
							<el-button
								v-else
								@click="handleWatch(scope.row)"
								type="text"
								size="small"
								>查看</el-button
							>
							<el-button
								@click="handleDel(scope.row)"
								type="text"
								size="small"
								class="div-table-button--delete"
								>删除</el-button
							>
						</template>
					</el-table-column>
				</el-table>

				<div>
					<el-pagination
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page.sync="pageNo"
						:page-sizes="[20, 50, 100, 200]"
						:page-size="parseInt(pageSize)"
						layout="sizes, prev, pager, next, total"
						:total="total"
					>
					</el-pagination>
				</div>
			</div>
		</div>
		<div
			v-if="
				pageType == 'dispose' || pageType == 'info' || pageType == 'add'
			"
		>
			<event-info
				ref="eleEditForm"
				:pageType="pageType"
				:eventId="eventId"
				:eventDetailData="eventDetailData"
				@handleClose="handleClose"
				@handleOk="handleOk"
				@dialogOk="handleEditSuccess"
			/>
		</div>

		<el-dialog
			:title="'播放语音'"
			:visible.sync="showVoice"
			width="40%"
			top="5vh"
			append-to-body
			class="dialog-h"
			:close-on-click-modal="false"
		>
			<div class="dialog-h-content scroll-h">
				<div
					style="display: flex; justify-content: center; margin: 50px"
				>
					<audio controls>
						<source :src="selVoiceUrl" type="" />
					</audio>
				</div>
			</div>

			<div class="resi-btns">
				<el-button size="small" @click="showVoice = false"
					>取消</el-button
				>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { requestPost } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";
import { mapGetters } from "vuex";
import eventInfo from "./cpts/event-info";
import axios from "axios";

export default {
	components: { eventInfo },

	data() {
		let endDisabledDate = (time) => {
			//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
			let nowData = Date.now();
			if (this.formData.startTime) {
				let startTime = new Date(this.formData.startTime);
				return (
					time.getTime() > nowData ||
					time.getTime() < startTime ||
					time.getTime() === startTime
				);
			} else {
				return time.getTime() > nowData;
			}
		};
		let startDisabledDate = (time) => {
			//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
			let nowData = Date.now();
			return time.getTime() > nowData;
		};

		return {
			tableLoading: false,
			pageType: "list", // 列表list 新增add  处理dispose 详情info
			user: {},
			agencyId: "",
			gridList: [], //所属网格list--场所区域
			agencyIdArray: [],
			orgOptions: [],
			orgOptionProps: {
				multiple: false,
				value: "agencyId",
				label: "agencyName",
				children: "subAgencyList",
				checkStrictly: true,
			},
			tableData: [],

			statusArray: [
				{
					value: "processing",
					label: "处理中",
				},
				{
					value: "closed_case",
					label: "已完成",
				},
			],
			qudaoArray: [
				// {
				//   value: "0",
				//   label: "随手拍/随时讲",
				// },
				// {
				//   value: "1",
				//   label: "多媒体反应",
				// },
				// {
				//   value: "2",
				//   label: "社区电话",
				// },
				// {
				//   value: "3",
				//   label: "12345",
				// },
				// {
				//   value: "4",
				//   label: "网络员手持终端",
				// },
			],

			formData: {
				gridId: "",
				agencyId: "",
				sourceType: "",
				eventContent: "",
				name: "",
				mobile: "",
				startTime: "",
				endTime: "",
				status: "",
				firstIdList: [],
				secondIdList: [],
			},
			cateOptions: [],
			eventTypeCheck: [],
			pageNo: 1,
			pageSize: window.localStorage.getItem("pageSize") || 20,
			total: 1,
			endPickerOptions: {
				disabledDate: endDisabledDate,
			},
			startPickerOptions: {
				disabledDate: startDisabledDate,
			},
			eventId: "",

			eventDetailData: {},

			showVoice: false,
			selVoiceUrl: "",

			multipleSelection: [],
		};
	},
	computed: {
		maxTableHeight() {
			return this.$store.state.inIframe
				? this.clientHeight - 410 + this.iframeHeigh
				: this.clientHeight - 410;
		},
		...mapGetters(["clientHeight", "iframeHeight"]),
	},
	watch: {
		"formData.endTime": function (val) {
			if (val && val != "") {
				let arrayTemp = val.split(" ");
				this.formData.endTime = arrayTemp[0] + " 23:59:59";
			}
		},
	},
	mounted() {
		console.log(this.$store.state);
		this.user = this.$store.state.user;

		this.agencyId = this.user.agencyId;
		this.getOrgTreeList();
		this.getTableData();
		this.getCateOptions();
		this.getQudaoOptions();
	},
	methods: {
		handleChangeAgency(val) {
			let obj = this.$refs["myCascader"].getCheckedNodes()[0].data;
			if (obj) {
				if (obj.level === "grid") {
					this.formData.gridId =
						this.agencyIdArray.length > 0
							? this.agencyIdArray[this.agencyIdArray.length - 1]
							: "";
					this.formData.agencyId = "";
				} else {
					this.formData.agencyId =
						this.agencyIdArray.length > 0
							? this.agencyIdArray[this.agencyIdArray.length - 1]
							: "";
					this.formData.gridId = "";
				}
			} else {
				this.formData.agencyId = "";
				this.formData.gridId = "";
			}
		},

		handleEventType(val) {
			// console.log('val-----eee', val)
			console.log("nodes---", this.$refs.cascaderEvent.getCheckedNodes());
			const nodes = this.$refs.cascaderEvent.getCheckedNodes();
			this.formData.firstIdList = [];
			this.formData.secondIdList = [];
			let level1 = nodes.filter((item) => item.level === 1);
			let level2 = nodes.filter((item) => item.level === 2);
			console.log("level2----1", level2);
			level1.forEach((item) => {
				console.log("level2----2", level2);
				if (item.hasChildren) {
					for (let i = level2.length - 1; i >= 0; i--) {
						if (level2[i].parent.value === item.value)
							level2.splice(i, 1);
					}
				}
			});
			this.formData.firstIdList = level1.map((item) => item.value);
			this.formData.secondIdList = level2.map((item) => item.value);
		},
		handleSelectionChange(val) {
			this.multipleSelection = [];
			val.forEach((element) => {
				this.multipleSelection.push(element.icEventId);
			});
			console.log(this.multipleSelection);
		},
		async handleMarkDiffcult() {
			const url = "/gov/project/icEvent/difficultpointevent";

			let params = {
				icEventIdList: this.multipleSelection,
				type: "1",
			};

			const { data, code, msg } = await requestPost(url, params);

			if (code === 0) {
				this.$message.success("标记成功");
				this.getTableData();
			} else {
				this.$message.error(msg);
			}
		},
		async handleCancalDiffcult() {
			const url = "/gov/project/icEvent/difficultpointevent";

			let params = {
				icEventIdList: this.multipleSelection,
				type: "0",
			};

			const { data, code, msg } = await requestPost(url, params);

			if (code === 0) {
				this.$message.success("取消标记成功");
				this.getTableData();
			} else {
				this.$message.error(msg);
			}
		},

		handleSearch(val) {
			console.log(this.formData);
			this.pageNo = 1;
			this.getTableData();
		},

		getOrgTreeList() {
			const { user } = this.$store.state;
			this.$http
				.post("/gov/org/customeragency/agencygridtree", {})
				.then(({ data: res }) => {
					if (res.code !== 0) {
						return this.$message.error(res.msg);
					} else {
						console.log("获取组织树成功", res.data);
						this.orgOptions = [];
						this.orgOptions.push(res.data);
					}
				})
				.catch(() => {
					return this.$message.error("网络错误");
				});
		},

		async handleExport() {
			const url = "/gov/project/icEvent/export";
			const { pageSize, pageNo, formData } = this;
			axios({
				url: window.SITE_CONFIG["apiURL"] + url,
				method: "post",
				data: {
					pageSize,
					pageNo,
					...formData,
				},
				responseType: "blob",
			})
				.then((res) => {
					let fileName = window.decodeURI(
						res.headers["content-disposition"]
							.split(";")[1]
							.split("=")[1]
					);
					console.log("filename", fileName);
					let blob = new Blob([res.data], {
						type: "application/vnd.ms-excel",
					});
					var url = window.URL.createObjectURL(blob);
					var aLink = document.createElement("a");
					aLink.style.display = "none";
					aLink.href = url;
					aLink.setAttribute("download", fileName);
					document.body.appendChild(aLink);
					aLink.click();
					document.body.removeChild(aLink); //下载完成移除元素
					window.URL.revokeObjectURL(url); //释放掉blob对象
				})
				.catch((err) => {
					console.log("获取导出情失败", err);
					return this.$message.error("网络错误");
				});
		},

		async handleAdd() {
			this.pageType = "add";
		},

		async handleWatch(row) {
			this.eventId = row.icEventId;
			const url = "/gov/project/icEvent/detail";
			// const url = "http://yapi.elinkservice.cn/mock/245/gov/project/icEvent/detail";

			const { data, code, msg } = await requestPost(url, {
				icEventId: this.eventId,
			});

			if (code === 0) {
				this.eventDetailData = { ...data };
				this.pageType = "info";
			} else {
				this.$message.error(msg);
			}
		},

		//加载组织数据
		async handleDispose(row) {
			this.eventId = row.icEventId;
			const url = "/gov/project/icEvent/detail";
			// const url = "http://yapi.elinkservice.cn/mock/245/gov/project/icEvent/detail";

			const { data, code, msg } = await requestPost(url, {
				icEventId: this.eventId,
			});

			if (code === 0) {
				this.eventDetailData = { ...data };
				this.pageType = "dispose";
			} else {
				this.$message.error(msg);
			}
		},

		//显示语音窗口
		handleShowVoice(url) {
			this.selVoiceUrl = url;
			this.showVoice = true;
		},

		handleClose() {
			this.pageType = "list";
			this.eventId = "";
			this.getTableData();
		},
		handleOk() {
			this.pageType = "list";
			this.eventId = "";
			this.pageNo = 1;
			this.getTableData();
		},

		handleEditSuccess() {
			this.handleClose();
			this.getTableData();
		},

		async handleDel(rowData) {
			let message = "确认删除?";

			this.$confirm(message, "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
				.then(() => {
					this.delEvent(rowData.icEventId);
				})
				.catch((err) => {});
		},
		async delEvent(eventId) {
			const url = "/gov/project/icEvent/delete";
			let idsArr = [eventId];

			const { data, code, msg } = await requestPost(url, idsArr);

			if (code === 0) {
				this.$message.success("删除成功！");
				this.getTableData();
			} else {
				this.$message.error("操作失败！");
			}
		},

		async getTableData() {
			this.tableLoading = true;
			const url = "/gov/project/icEvent/list";
			// const url = "http://yapi.elinkservice.cn/mock/245/gov/project/icEvent/list";
			const { pageSize, pageNo, formData } = this;
			const { data, code, msg } = await requestPost(url, {
				pageSize,
				pageNo,
				...formData,
			});

			this.tableLoading = false;
			if (code === 0) {
				this.total = data.total || 0;
				this.tableData = data.list
					? data.list.map((item) => {
							return item;
					  })
					: [];

				// this.tableData.forEach(item => {
				//   if (item.operationType === '2') {
				//     item.operationTypeShow = '已转服务'
				//   }
				//   if (item.operationType === '1') {
				//     item.operationTypeShow = '已立项'
				//   }
				//   if (item.operationType === '0') {
				//     item.operationTypeShow = '已回复'
				//   }

				// });
			} else {
				this.$message.error(msg);
			}
		},
		async getCateOptions() {
			const url = "/gov/issue/issueprojectcategorydict/list";

			const { data, code, msg } = await requestPost(url, {});

			if (code === 0) {
				this.cateOptions = this.deepTree(data, "subCategory");
			} else {
				this.$message.error(msg);
			}
		},

		async getQudaoOptions() {
			const url = "/sys/dict/data/dictlist";

			const { data, code, msg } = await requestPost(url, {
				dictType: "ic_event_source_type",
			});

			if (code === 0) {
				this.qudaoArray = data;
			} else {
				this.$message.error(msg);
			}
		},

		handleSizeChange(val) {
			this.pageSize = val;
			window.localStorage.setItem("pageSize", val);
			this.getTableData();
		},
		handleCurrentChange(val) {
			this.pageNo = val;
			this.getTableData();
		},

		resetSearch() {
			this.agencyIdArray = [];
			this.formData = {
				agencyId: "",
				gridId: "",
				sourceType: "",
				eventContent: "",
				name: "",
				mobile: "",
				startTime: "",
				endTime: "",
				status: "",
				firstIdList: [],
				secondIdList: [],
			};
			this.eventTypeCheck = [];

			this.pageNo = 1;
			this.getTableData();
			// this.loadTable()
		},
		deepTree(arr, child) {
			if (Array.isArray(arr) && arr.length > 0) {
				return arr.map((item) => {
					// if (child === 'subAgencyList') item.value = item.orgType + '-' + item.orgId
					return {
						...item,
						[child]:
							(item[child] &&
								item[child].length > 0 &&
								this.deepTree(item[child], child)) ||
							null,
					};
				});
			}
		},
	},
};
</script>

<style lang="scss" scoped>
@import "@/assets/scss/buttonstyle.scss";
@import "@/assets/scss/modules/management/list-main.scss";
@import "@/assets/scss/modules/shequzhili/event-info.scss";
.div_search {
	.item_width_2 {
		width: 200px;
	}
}
</style>
