<template>
	<zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title+'-列表', essential: true }]">
		<template slot-scope="{activeKey, data}">
			<template-page v-if="activeKey == 'list'" ref="pageRef" :get-list="getList" :table-attributes="tableAttributes" :table-events="tableEvents"
			  :options-evens-group="optionsEvensGroup" :moreParameters="moreParameters" :column-parsing="columnParsing"
			  :operation="operation()" :exportList="exportList">
			</template-page>
			<div v-if="~['add', 'edit', 'detail'].indexOf(activeKey)">
				<zj-form-container ref="formRef" :form-data="formData" :styleSwitch="false">
				  <zj-form-module title="" label-width="120px" :showPackUp="false"
				    :form-data="formData" :form-items="formItems" :bodyViewStyle="{
				      'max-height': '600px',
				      'overflow-y': 'auto'
				    }">
				  </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" @click="formConfirm(data.removeTab)" type="primary">确 定</el-button>
				</div>
			</div>
			<selectMember v-if="showSelectMember" :memberList="formData.userList" @cancelSelectMember="showSelectMember = false"
			  @selectMemberPass="selectMemberPass" />
			<selectGoods v-if="showSelectGoods" :goodsList="formData.goodsList" @cancelSelectGoods="showSelectGoods = false"
			  @selectGoodsPass="selectGoodsPass" />
		</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 { required, mobileRequired, mobile } from '@/components/template/rules_verify.js'
import { couponListPageV2, couponListPageV2Export, addCoupon, changeCouponFlag, editCoupon, getCouponDetail, getTagList, reissueCoupon } from "@/api/coupon";
import selectMember from "@/components/selectComponent/selectMember.vue"
import selectGoods from "@/components/selectComponent/selectGoods.vue"
import { MEMBER_CURRENT_TYPE_FILTER } from "@/filters/index.js"
import ImageUpload from '@/components/file-upload'
import operation_mixin from '@/components/template/operation_mixin.js'
export default {
  components: { TemplatePage, selectMember, selectGoods, ImageUpload },
  mixins: [import_mixin,operation_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ["新增", "编辑", "查看"],
      formDialog: false,
      formData: {
        couponName: "",
        couponAmount: "",
        couponType: "",
        orderAmount: "",
        activeType: 1,
        receiveCrowd: "",
        receiveLimitCount: "",
        shareTimes: "",
        couponValue: "",
        note: "",
        remark: "",
        flag: "",
        displayTime: "",
        activeDay: "",
        receiveDate: [],
        activeDate: [],
        imgSrc: [],
        userList: [],
        goodsList: [],
      },
      // 选择会员弹窗
      showSelectMember: false,
      showSelectGoods: false,
			formType: 'add',
			formVisible: false,
    }
  },
  computed: {
	// 事件组合
	optionsEvensGroup() {
		return [
			[
				[
					this.optionsEvensAuth("add", {
						click: () => {
							this.openForm('add')
						}
					})
				],
			]
		]
	},
    isService() {
      if (this.formData.receiveCrowd == 3) {
        return true;
      }
      if (this.formData.receiveCrowd == 2 && this.memberType == 'SERVICE') {
        return true;
      }
      return false;
    },
    memberType() {
      if (this.formData.userList.length > 0) {
        return this.formData.userList[0].type;
      } else {
        return '';
      }
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return [{
        md: 6,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入', disabled: this.formData.flag === 'START' || this.formDialogType == 2 },
        formItemAttributes: {
          label: '优惠券名称',
          prop: 'couponName',
          rules: [...required]
        }
      },
      {
        md: 6,
        isShow: true,
        name: 'el-radio',
        options: [{ label: "满减券", value: "SATISFY" }, { label: "商品券", value: "GOODS" }],
        attributes: { filterable: true, placeholder: '请选择', disabled: this.formData.flag === 'START' || this.formDialogType == 2 },
        formItemAttributes: {
          label: '优惠券类型',
          prop: 'couponType',
          rules: [...required]
        }
      },
      {
        md: 12,
        isShow: true,
        name: 'el-radio',
        options: [
          { label: "所有用户", value: 0 },
          { label: "所有会员", value: 4 },
          { label: "所有业务员", value: 3 },
          { label: "指定标签", value: 1 },
          { label: "指定会员", value: 2 },
        ],
        attributes: { filterable: true, placeholder: '请选择', disabled: this.formData.flag === 'START' || this.formDialogType == 2 },
        formItemAttributes: {
          label: '领取条件',
          prop: 'receiveCrowd',
          rules: [...required]
        }
      },
      {
        md: 24,
        isShow: this.formData.receiveCrowd === 2,
        name: 'slot-component',
        formItemAttributes: {
          label: '选择会员',
          prop: 'userList',
          rules: [...required]
        },
        render: (h, { props, onInput }) => {
          var { value } = props
          return (
            <div>
              <zj-table
                columns={[
                  {
                    columnAttributes: {
                      label: '头像',
                      prop: 'avatar',
                      width: '60px'
                    },
                    render: (h, { row, column, index }) => {
                      return <div style="width: 60px; height: 60px; overflow: hidden">
                        <el-image style="width: 60px; height: 60px" src={row.avatar} fit="fit"></el-image>
                      </div>
                    }
                  }, {
                    columnAttributes: {
                      label: '名称',
                      prop: 'nickName',
                    }
                  }, {
                    columnAttributes: {
                      label: '电话',
                      prop: 'mobile',
                    }
                  }, {
                    columnAttributes: {
                      label: '性别',
                      prop: 'sex',
                    }
                  }, {
                    columnAttributes: {
                      label: '地区',
                      prop: '',
                    },
                    render: (h, { row, column, index }) => {
                      return <div style="box-sizing: border-box; padding: 6px;">
                        {row.province + row.city}
                      </div>
                    }
                  }, {
                    columnAttributes: {
                      label: '角色',
                      prop: '',
                    },
                    render: (h, { row, column, index }) => {
                      return <div style="box-sizing: border-box; padding: 6px;">
                        {MEMBER_CURRENT_TYPE_FILTER(row.memberName)}
                      </div>
                    }
                  },
                  ...(() => {
                    if (this.formDialogType !== 2) {
                      return [
                        {
                          columnAttributes: {
                            label: '删除',
                            prop: '',
                            width: '100px'
                          },
                          render: (h, { row, column, index }) => {
                            return <div style="box-sizing: border-box; padding: 6px;">
                              <el-button type="text" onClick={() => {
                                this.formData.userList.splice(index, 1)
                              }}>删除</el-button>
                            </div>
                          }
                        }
                      ]
                    }
                    return []
                  })()
                ]}
                tableData={this.formData.userList}
                tableAttributes={{
                  size: 'mini',
                  border: true,
                }} />
              {this.formDialogType !== 2 ? <div style="display: flex;align-items: center;justify-content: center;border: 1px solid #EBEEF5;border-top: none;height: 50px;">
                <el-button type="text" onClick={() => {
                  this.showSelectMember = true
                }}>
                  添加会员
                </el-button>
              </div> : null}
            </div>
          )
        }
      },
      {
        md: 24,
        isShow: this.formData.couponType == 'GOODS',
        name: 'slot-component',
        formItemAttributes: {
          label: '指定商品',
          prop: 'goodsList',
          rules: [...required]
        },
        render: (h, { props, onInput }) => {
          var { value } = props
          return (
            <div>
              <zj-table
                columns={[
                  {
                    columnAttributes: {
                      label: '名称',
                      prop: 'goodsName',
                    }
                  },
                  ...(() => {
                    if (this.formDialogType !== 2) {
                      return [
                        {
                          columnAttributes: {
                            label: '删除',
                            prop: '',
                            width: '100px'
                          },
                          render: (h, { row, column, index }) => {
                            return <div style="box-sizing: border-box; padding: 6px;">
                              <el-button type="text" onClick={() => {
                                this.formData.goodsList.splice(index, 1)
                              }}>删除</el-button>
                            </div>
                          }
                        }
                      ]
                    }
                    return []
                  })()
                ]}
                tableData={this.formData.goodsList}
                tableAttributes={{
                  size: 'mini',
                  border: true,
                }} />
              {this.formDialogType !== 2 ? <div style="display: flex;align-items: center;justify-content: center;border: 1px solid #EBEEF5;border-top: none;height: 50px;">
                <el-button type="text" onClick={() => {
                  this.showSelectGoods = true
                }}>
                  添加商品
                </el-button>
              </div> : null}
            </div>
          )
        }
      },
      {
        md: 6,
        isShow: this.formData.couponType == 'SATISFY',
        name: 'el-input',
        attributes: { style: "width:100%", placeholder: '请输入', disabled: this.formData.flag === 'START' || this.formDialogType == 2 },
        formItemAttributes: {
          label: '订单满足金额',
          prop: 'orderAmount',
          rules: [...required]
        }
      },
      {
        md: 6,
        isShow: true,
        name: 'el-input',
        attributes: { style: "width:100%", placeholder: '请输入', disabled: this.formData.flag === 'START' || this.formDialogType == 2 },
        formItemAttributes: {
          label: '优惠券面值',
          prop: 'couponValue',
          rules: [...required]
        }
      },
      {
        md: 6,
        isShow: !this.isService,
        name: 'el-input',
        attributes: { style: "width:100%", placeholder: '请输入', disabled: this.formDialogType == 2 },
        formItemAttributes: {
          label: '发放数量',
          prop: 'couponAmount',
          rules: [...required]
        }
      }, {
        md: 6,
        isShow: this.isService,
        name: 'el-input',
        attributes: { style: "width:100%", placeholder: '请输入', disabled: this.formData.flag === 'START' || this.formDialogType == 2 },
        formItemAttributes: {
          label: '每人分享次数',
          prop: 'shareTimes',
          rules: [...required]
        }
      }, {
        md: 6,
        isShow: !this.isService,
        name: 'el-input',
        attributes: { style: "width:100%", placeholder: '请输入', disabled: this.formData.flag === 'START' || this.formDialogType == 2 },
        formItemAttributes: {
          label: '每人领用张数',
          prop: 'receiveLimitCount',
          rules: [...required]
        }
      },
      {
        md: 6,
        isShow: true,
        name: 'el-date-picker',
        attributes: { style: "width:100%", placeholder: '请输入', type: "datetime", "value-format": "yyyy-MM-dd HH:mm:ss", disabled: this.formData.flag === 'START' || this.formDialogType == 2 },
        formItemAttributes: {
          label: '显示时间',
          prop: 'displayTime',
          rules: [...required]
        }
      },
      {
        md: 6,
        isShow: true,
        name: 'el-date-picker',
        attributes: { style: "width:100%", placeholder: '请输入', type: "daterange", "value-format": "yyyy-MM-dd HH:mm:ss", disabled: this.formData.flag === 'START' || this.formDialogType == 2 },
        formItemAttributes: {
          label: '领取时间',
          prop: 'receiveDate',
          rules: [...required]
        }
      },
      {
        md: 6,
        isShow: true,
        name: 'el-date-picker',
        attributes: { style: "width:100%", placeholder: '请输入', type: "daterange", "value-format": "yyyy-MM-dd HH:mm:ss", disabled: this.formData.flag === 'START' || this.formDialogType == 2 },
        formItemAttributes: {
          label: '使用时间',
          prop: 'activeDate',
          rules: [...required]
        }
      },
      {
        md: 6,
        isShow: true,
        name: 'slot-component',
        formItemAttributes: {
          label: '有效时间',
          prop: 'activeDay',
          rules: []
        },
        render: (h, { props, onInput }) => {
          var { value } = props
          return <el-input style="width:100%" value={value} onInput={onInput} autocomplete="off" placeholder="请输入" disabled={this.formDialogType == 2}>
            <template slot="prepend">自领优惠券后</template>
            <template slot="append">天内有效</template>
          </el-input>
        }
      }, {
        md: 24,
        isShow: true,
        name: 'el-input',
        attributes: { style: "width:100%", placeholder: '请输入', type: "textarea", autosize: { minRows: 3, maxRows: 6 }, maxlength: "100", 'show-word-limit': true, disabled: this.formDialogType == 2 },
        formItemAttributes: {
          label: '使用说明',
          prop: 'note',
          rules: [...required]
        }
      }, {
        md: 24,
        isShow: true,
        name: 'el-input',
        attributes: { placeholder: '请输入', type: "textarea", autosize: { minRows: 3, maxRows: 6 }, maxlength: "100", 'show-word-limit': true, disabled: this.formDialogType == 2 },
        formItemAttributes: {
          label: '备注',
          prop: 'remark',
          rules: []
        }
      }, {
        md: 24,
        isShow: true,
        name: 'slot-component',
        formItemAttributes: {
          label: '弹窗图片',
          prop: 'imgSrc',
          rules: []
        },
        render: (h, { props, onInput }) => {
          var { value } = props
          return (
            <ImageUpload fileList={this.formData.imgSrc} uid="imgSrc666_materials_drawing_images" limit={1} isEdit={this.formDialogType !== 2} />
          )
        }
      },
      ]
    }
  },
  methods: {
    // 列表请求函数
    getList: couponListPageV2,
    // 列表导出函数
    exportList: couponListPageV2Export,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
	// 表格操作列
	operation() {
		return this.operationBtn({
			detail: {
				btnType: 'text',
				click: ({ row, index, column }) => {
					this.openForm('detail',row.couponId)
				}
				},
			edit: {
				btnType: 'text',
				conditions: ({ row, index, column }) => {
					return row.releaseFlag === 'WAIT'
				},
				click: ({ row, index, column }) => {
					this.openForm('edit',row.couponId)
				}
			},
			cancel: {
				btnType: 'text',
				prompt: '确定取消吗？',
				conditions: ({ row, index, column }) => {
					return row.releaseFlag === 'START'
				},
				click: ({ row, index, column }) => {
					changeFlag(row.couponId)
				}
			},
			reissue: {
				btnType: 'text',
				prompt:  '确定补发业务员优惠券吗？',
				conditions: ({ row, index, column }) => {
					return row.releaseFlag === 'START'
				},
				click: ({ row, index, column }) => {
					reissueCoupon(row.couponId)
				}
			},
		})
	},
    // 打开 新增编辑
    openForm(type, couponId) {
    	this.$refs.tabPage.addTab({
    		// 对应显示的模块
    		activeKey: type,
    		// 唯一标识
    		key: type,
    		// 页签名称
    		label: ({ edit: "编辑", add: "新增", detail: "查看" })[type],
    		// 打开时事件
    		triggerEvent: () => {
    			this.formCancel()
    			this.$nextTick(()=>{
    				this.formType = type
    				this.formVisible = true
    				if (type == 'add') {
    					this.formDialogType = 0
    				} else if(type == 'edit'){
    					this.formDialogType = 1
    					getCouponDetail({ couponId }).then(res => {
    						Object.assign(this.formData, res.data, {
    							receiveDate: res.data.obtainStartTime ? [res.data.obtainStartTime, res.data.obtainEndTime] : [],
    							activeDate: res.data.activeStartTime ? [res.data.activeStartTime, res.data.activeEndTime] : [],
    							imgSrc: res.data.imgSrc ? [{ url: res.data.imgSrc }] : [],
    						})
    					})
    				}else{
    					this.formDialogType = 2
    					getCouponDetail({ couponId }).then(res => {
    						Object.assign(this.formData, res.data, {
    							receiveDate: res.data.obtainStartTime ? [res.data.obtainStartTime, res.data.obtainEndTime] : [],
    							activeDate: res.data.activeStartTime ? [res.data.activeStartTime, res.data.activeEndTime] : [],
    							imgSrc: res.data.imgSrc ? [{ url: res.data.imgSrc }] : [],
    						})
    					})
    				}
    			})
    		},
    		// 关闭时事件
    		closeEvent: () => {
					this.formCancel()
    		}
    	})
    },
    formCancel() {
			this.formVisible = false
			this.$refs?.formRef?.resetFields()
			this.$data.formData = this.$options.data().formData
    },
    formConfirm(cancel) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          var pam = {
            ...this.formData,
            imgSrc: this.formData.imgSrc.map(item => item.url).join(","),
            activeStartTime: (this.formData.activeDate && this.formData.activeDate[0]) ? this.formData.activeDate[0].split(' ')[0] + ' 00:00:00' : '',
            activeEndTime: (this.formData.activeDate && this.formData.activeDate[1]) ? this.formData.activeDate[1].split(' ')[0] + ' 23:59:59' : '',
            obtainStartTime: this.formData.receiveDate[0].split(' ')[0] + ' 00:00:00',
            obtainEndTime: this.formData.receiveDate[1].split(' ')[0] + ' 23:59:59',
          };
          ([addCoupon, editCoupon][this.formDialogType])(pam).then(res => {
            this.$message({ type: 'success', message: `${this.formDialogTitles[this.formDialogType]}成功!` })
            cancel('list')
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },
    selectMemberPass(val) {
      this.formData.userList.push(...val)
    },
    selectGoodsPass(val) {
      this.formData.goodsList.push(...val)
    },
    // 操作 - 更改优惠券标志为取消
    changeFlag(couponId) {
      let params = {
        couponId: couponId,
        flag: 'CANCEL',
      }
      changeCouponFlag(params).then(() => {
        this.$message({ type: 'success', message: `取消成功` })
        this.$refs.pageRef.refreshList()
      })
    },
    reissueCoupon(couponId) {
      reissueCoupon({ couponId }).then(res => {
        this.$message({ type: 'success', message: `设置成功` })
        this.$refs.pageRef.refreshList()
      })
    },
  }
}
</script>

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