<template>
  <template-page ref="pageRef" :get-list="getList" :exportList="exportList" :table-attributes="tableAttributes"
    :table-events="tableEvents" :options-evens-group="optionsEvensGroup"
    :column-parsing="columnParsing" :operation="operation()">
    <div class="cartographer">
      <el-dialog :title="formData.id?'详情':'新增'" width="100%" :modal="false" :visible.sync="formDialog"
        :before-close="formCancel">
        <zj-form-container v-if="formDialog" ref="formRef" :form-data="formData" :styleSwitch="false">
          <zj-form-module title="活动信息" label-width="120px" :form-data="formData"
            :form-items="formItems">
          </zj-form-module>
          <zj-form-module title="活动填写内容" label-width="100px" :form-data="formData"
            :form-items="formItems2">
          </zj-form-module>
        </zj-form-container>
        <div slot="footer" class="dialog-footer">
          <el-button size="mini" @click="formCancel">取 消</el-button>
          <el-button v-if="!formData.id" size="mini" type="primary" @click="formConfirm">确 定</el-button>
          <el-button v-if="formData.id && !!~[2,3].indexOf(formData.status)" size="mini" type="primary" @click="zhongzhi">终 止</el-button>
        </div>
      </el-dialog>
    </div>
    <answer v-if="showQuestion" :defaultData="questionData" @close="questionClose" @confirm="questionConfirm"/>
  </template-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import operation_mixin from '@/components/template/operation_mixin.js'
import {promotionQuestionnaireList,promotionQuestionnaireExport,promotionQuestionnaireAdd,promotionQuestionnaireStop,promotionQuestionnaireDetail} from "@/api/setActivity.js"
import answer from "./answer.vue"
import ImageUpload from '@/components/file-upload'
import quillEditor from '@/components/v-quill-editor'
import editTable from "@/components/template/editTable.js"
import { required, mobileRequired, mobile, httpUrl, email } from '@/components/template/rules_verify.js'
export default {
  components: { TemplatePage, answer, ImageUpload, quillEditor },
  mixins: [import_mixin, operation_mixin, editTable],
  data() {
    return {
      formDialog: false,
      showQuestion: false,
      questionData: {
        rowIndex: -1
      },
      formData: {
        "companyWechatId": "",
        "companyWechatName": JSON.parse(localStorage.getItem('greemall_user')).companyName,
        "startTime": "",
        "endTime": "",
        "name": "",
        "submitLimit": '',
        "submitLimitBool": 0,
        "qrcode": "",
        "title": "",
        "content": "",
        "banner": [],
        "detailImgs": [],
        "promotionQuestionnaireItems": [],
        "promotionQuestionnaireUsers": [],
      },
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {},
    }
  },
  computed:{
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: this.addData
            })
          ]
        ]
      ]
    },
    formItems(){
      return [
        {
          name: 'el-input',
          md: 12,
          attributes: { disabled: true, placeholder: '请选择' },
          formItemAttributes: { label: '所属商户', prop: 'companyWechatName' }
        },
        {
          name: 'el-date-picker',
          md: 6,
          attributes: {
            disabled: !!this.formData.id,
            style: { width: '100%' },
            placeholder: '请选择',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
          },
          formItemAttributes: {
            label: '活动开始日期',
            prop: 'startTime',
            rules: [{ required: true, message: '请选择', trigger: 'blur' }]
          }
        },
        {
          name: 'el-date-picker',
          md: 6,
          attributes: {
            disabled: !!this.formData.id,
            style: { width: '100%' },
            placeholder: '请选择',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
          },
          formItemAttributes: {
            label: '活动结束日期',
            prop: 'endTime',
            rules: [{ required: true, message: '请选择', trigger: 'blur' }]
          }
        },
        {
          name: 'el-input',
          md: 12,
          attributes: { disabled: !!this.formData.id, placeholder: '请选择' },
          formItemAttributes: { 
            label: '活动名称', 
            prop: 'name',
            rules: [{ required: true, message: '请填写', trigger: 'blur' }]
          }
        },
        {
          name: 'el-input',
          md: 12,
          attributes: { disabled: !!this.formData.id, placeholder: '请选择' },
          formItemAttributes: { 
            label: '二维码主题', 
            prop: 'title',
            rules: [{ required: true, message: '请填写', trigger: 'blur' }]
          }
        },
        {
          md: 24,
          name: 'slot-component',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '提交次数',
            prop: 'submitLimitBool',
            rules: [{ required: true, message: '请选择', trigger: 'blur' }]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            console.log(value)
            return (
              <div class="redbordererr" style="">
                <el-form-item label="" label-width="0px" prop="submitLimit" rules={value ? [{ required: true, message: '请填写', trigger: 'blur' }] : []}>
                  <el-radio-group disabled={!!this.formData.id} value={value} onInput={onInput}>
                    <el-radio disabled={!!this.formData.id} label={0}>不限制</el-radio>
                    <el-radio disabled={!!this.formData.id} label={1}>
                        限制{value?[<el-input disabled={!!this.formData.id} style="margin: 0 10px;width:100px;" value={this.formData.submitLimit} onInput={(val)=>{this.formData.submitLimit = val}} type="number" placeholder="请输入内容"></el-input>,<span>次</span>]:null}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            )
          }
        },
        {
          md: 24,
          name: 'slot-component',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '首页广告图',
            prop: 'banner',
            rules: [{ required: true, message: '请上传', trigger: 'blur' }]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <ImageUpload isEdit={!this.formData.id} fileList={this.formData.banner} uid={`questionFiles_bananner`} limit={1} isUpdate={false} />
            )
          }
        },
        {
          md: 24,
          name: 'slot-component',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '活动详情图',
            prop: 'detailImgs',
            rules: [{ required: true, message: '请上传', trigger: 'blur' }]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <ImageUpload isEdit={!this.formData.id} fileList={this.formData.detailImgs} uid={`questionFiles_detaidetailImgsdetailImgs`} limit={100} isUpdate={false} />
            )
          }
        },
        {
          md: 24,
          name: 'slot-component',
          attributes: { placeholder: '请输入' },
          formItemAttributes: {
            label: '活动说明',
            prop: 'content',
            rules: []
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return (
              <quillEditor disabled={!!this.formData.id} value={value} onInput={onInput}></quillEditor>
            )
          }
        },
        {
          name: 'slot-component',
          md: 24,
          formItemAttributes: { 
            label: '提交记录', 
            prop: 'promotionQuestionnaireUsers',
            rules: [{ required: true, message: '请设置', trigger: 'blur' }]
          },
          render: (h, { props, onInput }) => {
            var { value } = props
            return this.convertTableJson(value, [
              {
                columnAttributes: {
                  label: '*姓名',
                  prop: 'name',
                },
                editRender: (h, { row, column, index }) => {
                  return (
                    <div class="redbordererr">
                      <el-form-item label="" label-width="0px" prop={`promotionQuestionnaireUsers.${index}.${column.columnAttributes.prop}`} rules={[{ required: true, message: '请填写', trigger: 'blur' }]}>
                        <el-input value={row[column.columnAttributes.prop]} onInput={val => { row[column.columnAttributes.prop] = val }} placeholder="请输入内容"></el-input>
                      </el-form-item>
                    </div>
                  )
                },
                viewRender: (h, { row, column, index }) => {
                  return <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
                }
              },
              {
                columnAttributes: {
                  label: '*电话',
                  prop: 'mobile',
                },
                editRender: (h, { row, column, index }) => {
                  return (
                    <div class="redbordererr">
                      <el-form-item label="" label-width="0px" prop={`promotionQuestionnaireUsers.${index}.${column.columnAttributes.prop}`} rules={mobileRequired}>
                        <el-input value={row[column.columnAttributes.prop]} onInput={val => { row[column.columnAttributes.prop] = val }} placeholder="请输入内容"></el-input>
                      </el-form-item>
                    </div>
                  )
                },
                viewRender: (h, { row, column, index }) => {
                  return <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
                }
              },
              {
                columnAttributes: {
                  label: '*时间（分钟）',
                  prop: 'min',
                },
                editRender: (h, { row, column, index }) => {
                  return (
                    <div class="redbordererr">
                      <el-form-item label="" label-width="0px" prop={`promotionQuestionnaireUsers.${index}.${column.columnAttributes.prop}`} rules={[{ required: true, message: '请填写', trigger: 'blur' }]}>
                        <el-input type="number" value={row[column.columnAttributes.prop]} onInput={val => { row[column.columnAttributes.prop] = val }} placeholder="请输入内容"></el-input>
                      </el-form-item>
                    </div>
                  )
                },
                viewRender: (h, { row, column, index }) => {
                  return <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
                }
              },
              {
                columnAttributes: {
                  label: '*备注',
                  prop: 'remark',
                },
                editRender: (h, { row, column, index }) => {
                  return (
                    <div class="redbordererr">
                      <el-form-item label="" label-width="0px" prop={`promotionQuestionnaireUsers.${index}.${column.columnAttributes.prop}`} rules={[{ required: true, message: '请填写', trigger: 'blur' }]}>
                        <el-input value={row[column.columnAttributes.prop]} onInput={val => { row[column.columnAttributes.prop] = val }} placeholder="请输入内容"></el-input>
                      </el-form-item>
                    </div>
                  )
                },
                viewRender: (h, { row, column, index }) => {
                  return <div style="padding-left:10px">{row[column.columnAttributes.prop]}</div>
                }
              },
            ], {
              isEdit: !this.formData.id,
              isAdd: !this.formData.id,
              isDel: !this.formData.id,
            }, {
              add: ()=>{
                this.formData.promotionQuestionnaireUsers.push({
                  "min": '',
                  "mobile": "",
                  "name": "",
                  "promotionQuestionnaireId": "",
                  "remark": ""
                })
                this.isEditTableIndex = this.formData.promotionQuestionnaireUsers.length - 1
              },
              delete: ({ row, column, index }, cb) => {
                if (this.isEditTableIndex == index) {
                  this.isEditTableIndex = -1
                } else if (this.isEditTableIndex > index) {
                  this.isEditTableIndex--
                }
                cb && cb()
              },
              verify: ({ row, column, index }, isEditTableIndex) => {
                return new Promise(r => {
                  if (isEditTableIndex > -1) {
                    this.$refs.formRef.validateField([
                      `promotionQuestionnaireUsers.${isEditTableIndex}.min`,
                      `promotionQuestionnaireUsers.${isEditTableIndex}.mobile`,
                      `promotionQuestionnaireUsers.${isEditTableIndex}.name`,
                      `promotionQuestionnaireUsers.${isEditTableIndex}.remark`,
                    ], (v) => {
                      if (v) {
                        r(true)
                      } else {
                        r(false)
                      }
                    })
                  } else {
                    r(true)
                  }
                })
              },
            })
          }
        },
      ]
    },
    formItems2(){
      return [{
        md: 24,
        name: 'slot-component',
        attributes: { placeholder: '请输入' },
        formItemAttributes: {
          label: '',
          'label-width': '0px',
          prop: 'promotionQuestionnaireItems',
          rules: [{ required: true, message: '请设置', trigger: 'blur' }]
        },
        render: (h, { props, onInput }) => {
          return (
            <div>
              <div>
                {!this.formData.id?<el-button type="primary" onClick={()=>{ this.showQuestion = true }}>新增</el-button>:null}
              </div>
              <div>
                <zj-table
                  columns={[{
                    columnAttributes: {
                      label: '填写内容',
                      prop: '',
                    },
                    render: (h, { row, column, index }) => {
                      return (
                        <div style="padding:6px;">
                          <div style="font-weight:bold;">{row.isRequire?<span style="color:red">*</span> : null}{index+1}、{row.question}（{['单选','多选','填写'][row.type-1]}）</div>
                          {[
                          <div>
                            {row.answer.map(item=><el-radio disabled label="">{item.option_value}</el-radio>)}
                          </div>,
                          <div>
                            {row.answer.map(item=><el-checkbox disabled label="">{item.option_value}</el-checkbox>)}
                          </div>,
                          <div>
                            <el-input disabled placeholder="请输入内容"></el-input>
                          </div>
                          ][row.type-1]}
                        </div>
                      )
                    },
                  },
                  ...(()=>{
                    if(!this.formData.id){
                      return[{
                        columnAttributes: {
                          label: '操作',
                          prop: '',
                          width: '200px'
                        },
                        render: (h, { row, column, index }) => {
                          return (
                            <div style="padding-left:5px">
                              <el-button size="mini" onClick={()=>{
                                this.questionData = {
                                  ...JSON.parse(JSON.stringify(row)),
                                  rowIndex: index
                                }
                                this.$nextTick(()=>{
                                  this.showQuestion = true
                                })
                              }}>编辑</el-button>
                              <el-button size="mini" onClick={()=>{
                                this.formData.promotionQuestionnaireItems.push({...JSON.parse(JSON.stringify(row))})
                              }}>复制</el-button>
                              <el-button size="mini" onClick={()=>{
                                this.formData.promotionQuestionnaireItems.splice(index, 1)
                              }}>删除</el-button>
                            </div>
                          )
                        },
                      }]
                    }
                    return []
                  })()]}
                  table-data={this.formData.promotionQuestionnaireItems}
                />
              </div>
            </div>
          )
        }
      }]
    }
  },
  methods: {
    // 列表请求函数
    getList:promotionQuestionnaireList,
    // 列表导出函数
    exportList: promotionQuestionnaireExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      if (item.jname === 'qrcode') {
				defaultData.render = (h, { row, index, column }) => {
					return (
						<div style="padding:0 6px;cursor: pointer;">
							{row.qrcode ? row.qrcode.split(",").map(url => <el-image src={url} preview-src-list={[url]} fit="fit" style="width:80px;height:80px;" />) : null}
						</div>
					)
				}
			}
      if (item.jname == 'startTime') {
				defaultData.render = (h, { row, index, column }) => {
					return (
						<div style="padding:0 6px;cursor: pointer;">
							{row.startTime.split(" ")[0]}
						</div>
					)
				}
			}
      if (item.jname == 'endTime') {
				defaultData.render = (h, { row, index, column }) => {
					return (
						<div style="padding:0 6px;cursor: pointer;">
							{row.endTime.split(" ")[0]}
						</div>
					)
				}
			}
      return defaultData
    },
    // 操作按钮
    operation() {
      return this.operationBtn({
        detail: {
          click: ({ row, index, column }) => {
            promotionQuestionnaireDetail({
              id: row.id
            }).then(res=>{
              this.formData = {
                ...res.data,
                submitLimitBool: res.data.submitLimit == -1 ? 0 : 1,
                promotionQuestionnaireItems:res.data.promotionQuestionnaireItems.map(item=>{
                  return {
                    ...item,
                    answer: JSON.parse(item?.answer||"[]")
                  }
                }),
                banner:res.data?.banner?.split(",").map(url=>({url})),
                detailImgs:res.data?.detailImgs?.split(",").map(url=>({url}))
              }
              this.$nextTick(()=>{
                this.formDialog = true
              })
            })
          }
        },
      })
    },
    // 新增
    addData(){
      this.formDialog = true
    },
    // 关闭弹窗
    formCancel(){
      this.formDialog = false
      this.$data.formData = this.$options.data().formData
    },
    // 确定
    formConfirm() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          var data = {
            ...this.formData,
            banner:this.formData.banner.map(item=>item.url).join(","),
            detailImgs:this.formData.detailImgs.map(item=>item.url).join(","),
            promotionQuestionnaireItems:this.formData.promotionQuestionnaireItems.map(item=>{
              return {
                ...item,
                answer: JSON.stringify(item.answer)
              }
            }),
            submitLimit: !!this.formData.submitLimitBool ? this.formData.submitLimit : -1
          }
          promotionQuestionnaireAdd(data).then(res=>{
            this.$message({
							type: 'success',
							message: `添加成功!`,
						})
						this.$refs.pageRef.refreshList()
            this.formCancel()
          })
        }
      })
    },
    // 终止
    zhongzhi(){
      promotionQuestionnaireStop({
        id:this.formData.id
      }).then(res=>{
        this.$message({
          type: 'success',
          message: `终止成功!`,
        })
        this.$refs.pageRef.refreshList()
        this.formCancel()
      })
    },
    // 关闭题目编辑
    questionClose(){
      this.showQuestion = false
      this.questionData = {
        rowIndex: -1
      }
    },
    // 确定题目编辑
    questionConfirm(data){
      if(data.rowIndex==-1){
        this.formData.promotionQuestionnaireItems.push({...data})
      }else{
        this.formData.promotionQuestionnaireItems.splice(data.rowIndex, 1, {...data})
      }
      this.questionClose()
    }
  }
}
</script>

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