<template>
	<zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title+'-列表', essential: true }]">
		<template slot-scope="{activeKey, data}">
			<div :style="{
				width: '100%',
				height: activeKey == 'list' ? '100%' : '0px',
				overflow: 'hidden'
			}">
				<template-page ref="pageRef" :get-list="getList" :table-attributes="tableAttributes" :table-events="tableEvents"
					:operationColumnWidth="200" :options-evens-group="optionsEvensGroup" :moreParameters="moreParameters"
					:column-parsing="columnParsing" :operation="operation" :exportList="exportList">
					<div slot="moreSearch">
						<el-radio-group v-model="status" size="mini" @change="changeType">
							<el-radio-button label="">全部</el-radio-button>
							<el-radio-button label="NO">未发布</el-radio-button>
							<el-radio-button label="YES">已发布</el-radio-button>
						</el-radio-group>
						<br><br>
					</div>
				</template-page>
			</div>
			<div v-if="~['add', 'edit'].indexOf(activeKey)" style="box-sizing: border-box;padding: 16px;">
				<zj-form-container ref="formRef" :form-data="formData" :styleSwitch="false">
					<zj-form-module :title="data.label" label-width="100px" :showPackUp="false" :form-data="formData"
						:form-items="formItems">
					</zj-form-module>
				</zj-form-container>
				<div slot="footer" class="dialog-footer">
					<el-button size="mini" @click="data.removeTab()">取 消</el-button>
					<el-button v-if="formDialogType < 2" size="mini" type="primary"
						@click="formConfirm('NO', data.removeTab)">保存</el-button>
					<el-button v-if="formDialogType < 2" size="mini" type="primary"
						@click="formConfirm('YES', data.removeTab)">发布</el-button>
				</div>
			</div>
			<div v-if="~['detail'].indexOf(activeKey)" style="box-sizing: border-box;padding: 16px;">
				<zj-form-container ref="formRef" :form-data="formData" :styleSwitch="false">
					<zj-form-module :title="data.label" label-width="100px" :showPackUp="false" :form-data="formData"
						:form-items="formItems2">
					</zj-form-module>
				</zj-form-container>
				<div slot="footer" class="dialog-footer">
					<el-button size="mini" @click="data.removeTab()">取 消</el-button>
				</div>
			</div>
		</template>
	</zj-tab-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import ImageUpload from '@/components/file-upload'
import { required, mobileRequired, mobile } from '@/components/template/rules_verify.js'
import { noticeListPageV2, noticePageExport, getNoticeDetail, noticeAdd, noticeUpdate, noticeDel } from "@/api/announcement";
import { memberListPageV2 } from "@/api/masterManagement";
import { getMemberList } from "@/api/member";
import { getList as getListaa } from "@/api/merchant";
export default {
	components: { TemplatePage, ImageUpload },
	mixins: [import_mixin],
	data() {
		return {
			// 事件组合
			optionsEvensGroup: [
				[
					[
						{
							name: '新建',
							click: this.addData
						}
					],
				],
			],
			// 表格属性
			tableAttributes: {
				// 启用勾选列
				selectColumn: false
			},
			// 表格事件
			tableEvents: {
				'selection-change': this.selectionChange
			},
			// 勾选选中行
			recordSelected: [],
			/** 表单变量 */
			formDialogType: 0,
			formData: {
				type: "A",
				title: "",
				files: [],
				adminWebsitIds: [],
				adminNickName: "",
				workerIds: [],
				content: "",
			},
			status: '',
			websitList: [],
			workerList: []
		}
	},
	computed: {
		// 更多参数
		moreParameters() {
			return []
		},
		formItems() {
			return [{
				md: 24,
				isShow: true,
				name: 'el-radio',
				options: [
					{
						label: `活动`,
						value: "A"
					},
					{
						label: `公告`,
						value: "B"
					}],
				attributes: { filterable: true, placeholder: '请选择', disabled: this.formDialogType == 2 },
				formItemAttributes: {
					label: '类型',
					prop: 'type',
					rules: [...required]
				},
			},
			{
				md: 24,
				isShow: true,
				name: 'el-input',
				attributes: { placeholder: '请输入', disabled: this.formDialogType == 2 },
				formItemAttributes: {
					label: '标题',
					prop: 'title',
					rules: [...required]
				}
			},
			{
				md: 24,
				isShow: this.formDialogType < 2 && JSON.parse(localStorage.getItem("greemall_user")).type == 2,
				name: 'zj-paging-pull-down',
				options: this.websitList,
				attributes: {
					valueKey: "adminUserId",
					labelKey: "companyName",
					size: 'mini',
					placeholder: '请选择',
					multiple: true
				},
				formItemAttributes: {
					label: '选择商户',
					prop: 'adminWebsitIds',
					rules: [...required]
				}
			},
			{
				md: 24,
				isShow: this.formDialogType < 2 && JSON.parse(localStorage.getItem("greemall_user")).type != 2,
				name: 'zj-paging-pull-down',
				options: this.workerList,
				attributes: {
					valueKey: "userId",
					labelKey: "nickName",
					size: 'mini',
					placeholder: '请选择',
					multiple: true
				},
				formItemAttributes: {
					label: '选择师傅',
					prop: 'workerIds',
					rules: [...required]
				}
			},
			{
				md: 24,
				isShow: true,
				name: 'slot-component',
				formItemAttributes: {
					label: '附件',
					prop: 'files',
					rules: this.formData.type == "A" ? [...required] : []
				},
				render: (h, { props, onInput }) => {
					var { value } = props
					return (
						<ImageUpload fileList={this.formData.files} uid="idcardUpUrl_drawing_aiuh" limit={100} isEdit={this.formDialogType !== 2} />
					)
				}
			},
			{
				md: 24,
				isShow: true,
				name: 'slot-component',
				formItemAttributes: {
					label: '内容',
					prop: 'content',
					rules: [...required]
				},
				render: (h, { props, onInput }) => {
					var { value } = props
					return (
						<v-quill-editor value={value} onInput={onInput} disabled={this.formDialogType == 2} />
					)
				}
			}]
		},
		formItems2() {
			return [{
				md: 24,
				isShow: true,
				name: 'slot-component',
				formItemAttributes: {
					prop: 'type',
					label: '',
					'label-width': "0px"
				},
				render: (h, { props, onInput }) => {
					var { value } = props
					return <div>类型：{({ A: "活动", B: "公告" })[value]}</div>
				}
			},
			{
				md: 24,
				isShow: true,
				name: 'slot-component',
				attributes: { placeholder: '请输入', disabled: true },
				formItemAttributes: {
					prop: 'title',
					label: '',
					'label-width': "0px"
				},
				render: (h, { props, onInput }) => {
					var { value } = props
					return <div>标题：{value}</div>
				}
			},
			{
				md: 24,
				isShow: true,
				name: 'slot-component',
				formItemAttributes: {
					prop: 'content',
					label: '',
					'label-width': "0px"
				},
				render: (h, { props, onInput }) => {
					var { value } = props
					return <div domPropsInnerHTML={value}></div>
				}
			},
			{
				md: 24,
				isShow: true,
				name: 'slot-component',
				formItemAttributes: {
					prop: 'files',
					label: '',
					'label-width': "0px"
				},
				render: (h, { props, onInput }) => {
					var { value } = props
					return (
						<ImageUpload fileList={this.formData.files} uid="idcardUpUrl_drawing_aiuh888" limit={100} isEdit={false} />
					)
				}
			},
			{
				md: 24,
				isShow: JSON.parse(localStorage.getItem("greemall_user")).type == 2,
				name: 'slot-component',
				formItemAttributes: {
					prop: 'adminWebsitIds',
					label: '',
					'label-width': "0px"
				},
				render: (h, { props, onInput }) => {
					var { value } = props
					return <div>{this.websitList.filter(item => !!~value.indexOf(item.adminUserId)).map(item => <el-tag style="margin-right:5px">{item.companyName}</el-tag>)}</div>
				},
			},
			{
				md: 24,
				isShow: JSON.parse(localStorage.getItem("greemall_user")).type != 2,
				name: 'slot-component',
				options: this.workerList,
				formItemAttributes: {
					prop: 'workerIds',
					label: '',
					'label-width': "0px"
				},
				render: (h, { props, onInput }) => {
					var { value } = props
					return <div>{this.workerList.filter(item => !!~value.indexOf(item.userId)).map(item => <el-tag style="margin-right:5px">{item.nickName}</el-tag>)}</div>
				},
			}]
		}
	},
	created() {
		if (this.$route.query.id) {
			this.getNoticeDetail(this.$route.query.id, 2, 'formDialog2')
		}
	},
	methods: {
		// 切换状态
		changeType(val) {
			this.$refs.pageRef.refreshList()
		},
		// 列表请求函数
		getList(p) {
			try {
				var pam = JSON.parse(JSON.stringify(p))
				if (this.status) {
					pam.params.push({ "param": "nr.status", "compare": "=", "value": this.status })
				}
				return noticeListPageV2(pam)
			} catch (error) {
				console.log(error)
			}
		},
		// 列表导出函数
		exportList: noticePageExport,
		// 表格列解析渲染数据更改
		columnParsing(item, defaultData) {
			return defaultData
		},
		// 监听勾选变化
		selectionChange(data) {
			this.recordSelected = data
		},
		getNoticeDetail(noticeId, type, name) {
			getNoticeDetail({
				noticeId
			}).then(res => {
				Object.assign(this.formData, res.data, {
					files: res.data.files ? res.data.files.map(item => ({
						...item,
						size: item.fileSize,
						type: item.fileType,
					})) : []
				})
				this.formDialogType = type
				this.openForm(name)
			})
		},
		// 表格操作列
		operation(h, { row, index, column }) {
			return (<div class='operation-btns'>
				{row.status == "NO" ? <el-button type="text" onClick={() => {
					this.$refs.tabPage.addTab({
						activeKey: "edit",
						key: "edit",
						label: "编辑",
						triggerEvent: () => {
							this.formCancel()
							this.$nextTick(() => {
								getNoticeDetail({
									noticeId: row.noticeId
								}).then(res => {
									Object.assign(this.formData, res.data, {
										files: res.data.files ? res.data.files.map(item => ({
											...item,
											size: item.fileSize,
											type: item.fileType,
										})) : []
									})
									this.formDialogType = 1
									this.openForm()
								})
							})
						},
						closeEvent: () => {
						}
					})
				}}>编辑</el-button> : null}
				<el-button type="text" onClick={() => {
					this.$refs.tabPage.addTab({
						activeKey: "detail",
						key: "detail",
						label: "查看",
						triggerEvent: () => {
							this.formCancel()
							this.$nextTick(() => {
								getNoticeDetail({
									noticeId: row.noticeId
								}).then(res => {
									Object.assign(this.formData, res.data, {
										files: res.data.files ? res.data.files.map(item => ({
											...item,
											size: item.fileSize,
											type: item.fileType,
										})) : []
									})
									this.formDialogType = 2
									this.openForm()
								})
							})
						},
						closeEvent: () => {
						}
					})
				}}>查看</el-button>
				{row.status == "NO" ? <el-popconfirm
					title={`是否确定删除？`}
					onConfirm={() => {
						noticeDel({
							noticeIds: row.noticeId
						}).then(res => {
							this.$message({
								type: 'success',
								message: '删除成功!'
							})
							this.$refs.pageRef.refreshList()
						})
					}}
				>
					<el-button type="text" style="color: #ff0000" slot="reference">删除</el-button>
				</el-popconfirm> : null}
				{row.status == "YES" ? <el-button style="color: #f5680e" type="text" onClick={() => {
					this.$router.push({
						name: 'readRecords',
						query: {
							id: row.noticeId
						}
					})
				}}>已读记录</el-button> : null}
			</div>)
		},
		addData() {
			this.$refs.tabPage.addTab({
				activeKey: "add",
				key: "add",
				label: "新增",
				triggerEvent: () => {
					this.formCancel()
					this.$nextTick(() => {
						this.formDialogType = 0
						this.openForm()
					})
				},
				closeEvent: () => {
				}
			})
		},
		openForm() {
			if (JSON.parse(localStorage.getItem("greemall_user")).type == 2) {
				getListaa({ pageNum: 1, pageSize: -1, type: 1 }).then((res) => {
					this.websitList = res.data.records
				})
			} else {
				getMemberList({ "pageNum": 1, "pageSize": -1, type: "WORKER" }).then(res => {
					this.workerList = res.data.records
				})
			}
		},
		formCancel() {
			this.$refs?.formRef?.$refs?.inlineForm?.clearValidate()
			this.$data.formData = this.$options.data().formData
			this.websitList = []
		},
		formConfirm(status, removeTab) {
			this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
				if (valid) {
					[noticeAdd, noticeUpdate][this.formDialogType]({
						...this.formData,
						files: this.formData.files.map(item => ({
							...item,
							fileSize: item.size,
							fileType: item.type,
						})),
						status
					}).then(res => {
						this.$message({
							type: 'success',
							message: status == "YES" ? '发送成功!' : '保存成功!'
						})
						removeTab('list')
						this.$refs.pageRef.refreshList()
					})
				}
			})
		},
	}
}
</script>

<style lang="scss" scoped></style>