<template>
	<template-page ref="pageRef" :get-list="getList" :table-attributes="tableAttributes" :table-events="tableEvents"
		:operationColumnWidth="80" :options-evens-group="optionsEvensGroup" :moreParameters="moreParameters"
		:column-parsing="columnParsing" :operation="operation()" :exportList="exportList" :replaceOrNotMap="true" expCode="exp_wx">
	</template-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, httpUrl, email } from '@/components/template/rules_verify.js'
import { del, getMainList, getTypeList } from "@/api/workOrder/settlementStandardInstall";
import { listPageV2, pageExport, add, edit } from "@/api/workOrder/settlementStandardRepair";
import { getSourceList } from "@/api/workOrder/settlementStandardInstall";
import { thousands } from '@/utils/common'
import operation_mixin from '@/components/template/operation_mixin.js'
export default {
	components: { TemplatePage, ImageUpload },
	mixins: [import_mixin, operation_mixin],
	data() {
		return {
			// 表格属性
			tableAttributes: {
				// 启用勾选列
				selectColumn: false
			},
			// 表格事件
			tableEvents: {
				'selection-change': this.selectionChange
			},
			// 勾选选中行
			recordSelected: [],
			/** 表单变量 */
			formDialogType: 0,
			formDialogTitles: ["新增", "编辑", "详情"],
			formDialog: false,
			formData: {
				companyName: JSON.parse(localStorage.getItem('greemall_user')).companyName,
			},
			editIndex: null,
			mainList: [],
			smallList: [],
			typeList: [],
			sourceList: []
		}
	},
	computed: {
		// 事件组合
		optionsEvensGroup() {
			return [
				[
					[
						this.optionsEvensAuth("add_wx", {
							click: this.addData
						})
					]
				]
			]
		},
		// 更多参数
		moreParameters() {
			return []
		},
		formItems() {
			return []
		}
	},
	created() {
		this.getMainList()
		this.getTypeList()
		this.getSourceList()
	},
	methods: {
		// 列表请求函数
		getList: listPageV2,
		getList(p) {
			try {
				var pam = JSON.parse(JSON.stringify(p))
				this.editIndex = null
				return listPageV2(pam)
			} catch (error) {
				console.log(error)
			}
		},
		// 列表导出函数
		exportList: pageExport,
		// 表格列解析渲染数据更改
		columnParsing(item, defaultData) {
			if (item.jname === 'orderChannelText') {
				defaultData.render = (h, { row, index, column }) => {
					return this.editIndex == index ? (
						<div class="redbordererr">
							<el-form-item prop={`tableData.${index}.orderChannelId`} rules={[{ required: true, message: '工单来源不能为空', trigger: 'blur' }]}>
								<el-select value={{ dictCode: row.orderChannelId, dictValue: row.orderChannelText }} value-key="dictCode" placeholder="请选择"
									onInput={(val) => {
										row.orderChannelText = val.dictValue
										row.orderChannelId = val.dictCode
									}}>
									{
										this.sourceList.map((item, index) => {
											return <el-option key={item.dictCode} label={item.dictValue} value={item}></el-option>
										})
									}
								</el-select>
							</el-form-item>
						</div>
					) : (<div style="padding: 6px;">{row.orderChannelText}</div>)
				}
			}
			if (item.jname === 'typeName') {
				defaultData.render = (h, { row, index, column }) => {
					return this.editIndex == index ? (
						<div class="redbordererr">
							<el-form-item prop={`tableData.${index}.type`} rules={[{ required: true, message: '工单类型不能为空', trigger: 'blur' }]}>
								<el-select value-key="id" value={{ orderSmallTypeText: row.typeName, id: row.type }} placeholder="请选择"
									onInput={(val) => {
										row.type = val.id
										row.typeName = val.orderSmallTypeText
									}}>
									{
										this.typeList.map((item, index) => {
											return <el-option key={item.id} label={item.orderSmallTypeText} value={item}></el-option>
										})
									}
								</el-select>
							</el-form-item>
						</div>
					) : (<div style="padding: 6px;">{row.typeName}</div>)
				}
			}
			if (item.jname === 'parentCategoryName') {
				defaultData.render = (h, { row, index, column }) => {
					return this.editIndex == index ? (
						<div class="redbordererr">
							<el-form-item prop={`tableData.${index}.parentCategoryId`} rules={[{ required: true, message: '产品大类不能为空', trigger: 'blur' }]}>
								<el-select value={{ categoryId: row.parentCategoryId, name: row.parentCategoryName }} value-key="name" placeholder="请选择"
									onInput={(val) => {
										row.parentCategoryId = val.categoryId
										row.parentCategoryName = val.name
										row.categoryName = ''
										row.categoryId = ''
										this.smallList = [...[{ name: '通用', categoryId: '0' }], ...(val.children ? val.children : [])]
									}}>
									{
										this.mainList.map((item, index) => {
											return <el-option key={item.categoryId} label={item.name} value={item}></el-option>
										})
									}
								</el-select>
							</el-form-item>
						</div>
					) : (<div style="padding: 6px;">{row.parentCategoryName}</div>)
				}
			}
			if (item.jname === 'categoryName') {
				defaultData.render = (h, { row, index, column }) => {
					return this.editIndex == index ? (
						<div class="redbordererr">
							<el-form-item prop={`tableData.${index}.categoryId`} rules={[{ required: true, message: '产品小类不能为空', trigger: 'blur' }]}>
								<el-select value={{ categoryId: row.categoryId, name: row.categoryName }} value-key="name" placeholder="请选择"
									onInput={(val) => {
										row.categoryName = val.name
										row.categoryId = val.categoryId
									}}>
									{
										this.smallList.map((item, index) => {
											return <el-option key={item.id} label={item.name} value={item}></el-option>
										})
									}
								</el-select>
							</el-form-item>
						</div>
					) : (<div style="padding: 6px;">{row.categoryName}</div>)
				}
			}
			if (item.jname === 'label') {
				defaultData.render = (h, { row, index, column }) => {
					return this.editIndex == index ? (
						<div class="redbordererr">
							<el-form-item prop={`tableData.${index}.label`} rules={[{ required: true, message: '质保类型不能为空', trigger: 'blur' }]}>
								<el-select value={row.label} placeholder="请选择"
									onInput={(val) => {
										row.label = val
									}}>
									{
										[{ id: 'INSIDE', name: '保内' }, { id: 'OUT', name: '保外' }].map((item, index) => {
											return <el-option key={item.id} label={item.name} value={item.id}></el-option>
										})
									}
								</el-select>
							</el-form-item>
						</div>
					) : (<div style="padding: 6px;">{row.label}</div>)
				}
			}
			if (item.jname === 'repairAmount') {
				defaultData.render = (h, { row, index, column }) => {
					return this.editIndex == index ? (
						<div class="redbordererr">
							<el-form-item prop={`tableData.${index}.repairAmount`} rules={[{ required: true, message: '上门票不能为空', trigger: 'blur' }]}>
								<el-input type="text" value={row.repairAmount} placeholder="请输入"
									onInput={(val) => {
										row.repairAmount = val
									}}>
								</el-input>
							</el-form-item>
						</div>
					) : (<div style="padding: 6px;">{thousands(row.repairAmount)}</div>)
				}
			}
			if (item.jname === 'normAmount') {
				defaultData.render = (h, { row, index, column }) => {
					return this.editIndex == index ? (
						<div class="redbordererr">
							<el-form-item prop={`tableData.${index}.normAmount`} rules={[{ required: true, message: '维修费结算比例不能为空', trigger: 'blur' },{ pattern:/^[1-9]\d*$/, message: '请输入大于0的正整数', trigger: 'blur' }]}>
								<div style="display:flex;">
									<el-input type="text" value={row.normAmount} placeholder="请输入大于0的正整数"
										onInput={(val) => {
											row.normAmount = val
										}}>
									</el-input>
								</div>
							</el-form-item>
						</div>
					) : (<div style="padding: 6px;">{row.normAmount} %</div>)
				}
			}
			if (item.jname === 'remark') {
				defaultData.render = (h, { row, index, column }) => {
					return this.editIndex == index ? (
						<div class="redbordererr">
							<el-form-item prop={`tableData.${index}.remark`}>
								<el-input type="text" value={row.remark} placeholder="请输入"
									onInput={(val) => {
										row.remark = val
									}}>
								</el-input>
							</el-form-item>
						</div>
					) : (<div style="padding: 6px;">{row.remark}</div>)
				}
				defaultData.columnAttributes.width = 200
			}
			return defaultData
		},
		// 监听勾选变化
		selectionChange(data) {
			this.recordSelected = data
		},


		operation() {
			return this.operationBtn({
				edit_wx: {
					conditions: ({ row, index, column }) => {
						return row.id
					},
					name: ({ row, index, column }) => {
						return this.editIndex == index ? '确定' : '编辑'
					},
					click: ({ row, index, column }) => {
						this.$refs.pageRef.tableForm().validate((valid) => {
							if (valid) {
								if (this.editIndex != index) {
									row = Object.assign(row, {
										label: row.label == '保内' ? 'INSIDE' : 'OUT'
									})
									this.mainList.forEach(item => {
										if (item.categoryId == row.parentCategoryId) {
											this.smallList = [...[{ name: '通用', categoryId: '0' }], ...(item.children ? item.children : [])]
										}
									})
									this.editIndex = index
								} else {
									this.edit(row)
								}
							} else {
								console.log('error submit!!');
								return false;
							}
						});
					}
				},
				save_wx: {
					conditions: ({ row, index, column }) => {
						return !row.id
					},
					click: ({ row, index, column }) => {
						this.$refs.pageRef.tableForm().validate((valid) => {
							if (valid) {
								this.add(row)
							} else {
								console.log('error submit!!');
								return false;
							}
						});
					}
				},
				del_wx: {
					prompt: "请确认是否删除该数据, 是否继续?",
					click: ({ row, index, column }) => {
						if (row.id) {
							del({
								id: row.id
							}).then(res => {
								if (res.code == 200) {
									this.$message({ type: 'success', message: '删除成功!' })
									this.$refs.pageRef.refreshList()
								} else {
									this.$message.error(res.msg);
								}
							})
						} else {
							this.$refs.pageRef.deleteRowData(0);
							this.editIndex = null
						}
					}
				}
			})
		},

		getMainList() {
			getMainList({ type: 2 }).then(res => {
				this.mainList = res.data
			})
		},
		getTypeList() {
			getTypeList({ pageNum: 1, pageSize: -1, params: [{ param: 'a.order_type', compare: '=', value: 'REPAIR' }, { param: 'a.status', compare: '=', value: true }] }).then(res => {
				this.typeList = res.data.records
			})
		},
		getSourceList(){
			getSourceList({ pageNum: 1, pageSize: -1, params: [{param: "a.dict_type", compare: "=", value: "ORDER_CHANNEL"}] }).then(res => {
				this.sourceList = [...[{ dictValue: '通用', dictCode: '0' }], ...res.data.records]
			})
		},
		addData() {
			this.$refs.pageRef.tableForm().validate((valid) => {
				if (valid) {
					this.editIndex = 0
					this.$refs.pageRef.insertionData(0, {
						companyWechatName: JSON.parse(localStorage.getItem('greemall_user')).companyName,
						settleNormType: 'REPAIR',
						orderChannelText: '',
						orderChannelId: '',
						typeName: '',
						type: '',
						categoryName: '',
						categoryId: '',
						parentCategoryName: '',
						parentCategoryId: '',
						label: '',
						normAmount: '',
						repairAmount: '',
						remark: ''
					})
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		openForm() {
			this.formDialog = true;
		},
		add(row) {
			add({
				settleNormType: 'REPAIR',
				orderChannelText: row.orderChannelText,
				orderChannelId: row.orderChannelId,
				typeName: row.typeName,
				type: row.type,
				parentCategoryName: row.parentCategoryName,
				parentCategoryId: row.parentCategoryId,
				categoryName: row.categoryName,
				categoryId: row.categoryId,
				label: row.label,
				normAmount: row.normAmount,
				repairAmount: row.repairAmount,
				remark: row.remark
			}).then(res => {
				if (res.code == 200) {
					this.editIndex = null
					this.$message({ type: 'success', message: `保存成功!` })
					this.$refs.pageRef.refreshList()
				}
			})
		},
		edit(row) {
			edit({
				id: row.id,
				settleNormType: 'REPAIR',
				orderChannelText: row.orderChannelText,
				orderChannelId: row.orderChannelId,
				typeName: row.typeName,
				type: row.type,
				parentCategoryName: row.parentCategoryName,
				parentCategoryId: row.parentCategoryId,
				categoryName: row.categoryName,
				categoryId: row.categoryId,
				label: row.label,
				normAmount: row.normAmount,
				repairAmount: row.repairAmount,
				remark: row.remark
			}).then(res => {
				if (res.code == 200) {
					this.editIndex = null
					this.$message({ type: 'success', message: `保存成功!` })
					this.$refs.pageRef.refreshList()
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.tab {
	padding: 20px 20px 0 20px;
}

.redbordererr {
	::v-deep .el-form-item {
		margin: 0 !important;
		overflow: hidden;
	}
}
</style>
