<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()"
    :operationColumnWidth="250"
    :moreParameters="moreParameters"
  >
    <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>
          <formModule :item="formData" :typeView="typeView"></formModule>
          <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 && qx(formData)" size="mini" type="primary" @click="zhongzhi">终 止</el-button>
          <el-button v-if="qx(formData)" size="mini" type="primary" @click="formConfirm">确 定</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,
  promotionQuestionnaireShow
} 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'
import formModule from './formModule.vue'
export default {
  components: { TemplatePage, answer, ImageUpload, quillEditor, formModule },
  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: [],
        promotionQuestionnaireQrcodes: []
      },
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {},
      typeView: 0
    }
  },
  computed: {
    moreParameters() {
      return [
        {
          name: '状态',
          key: 'status',
          value: '',
          conditions: [
            {
              label: '生效中',
              value: '1'
            },
            {
              label: '待生效',
              value: '0'
            },
            {
              label: '已过期',
              value: '2'
            },
            {
              label: '已终止',
              value: '3'
            },
            {
              label: '全部',
              value: ''
            }
          ]
        }
      ]
    },
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: this.addData
            })
          ]
        ]
      ]
    },
    formItems() {
      return [
        {
          name: 'el-date-picker',
          md: 6,
          attributes: {
            disabled: !this.qx(this.formData),
            style: { width: '100%' },
            placeholder: '请选择',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
            'picker-options': {
              disabledDate: time => {
                return time.getTime() < Date.now() - 86400000
              }
            }
          },
          formItemAttributes: {
            label: '活动开始日期',
            prop: 'startTime',
            rules: [{ required: true, message: '请选择', trigger: 'blur' }]
          },
          events: {
            change: () => {
              this.formData.endTime = ''
            }
          }
        },
        {
          name: 'el-date-picker',
          md: 6,
          attributes: {
            disabled: !this.qx(this.formData),
            style: { width: '100%' },
            placeholder: '请选择',
            'value-format': 'yyyy-MM-dd HH:mm:ss',
            'picker-options': {
              disabledDate: time => {
                if (this.formData.startTime) {
                  return time.getTime() < new Date(this.formData.startTime).getTime()
                }
                return true
              }
            }
          },
          formItemAttributes: {
            label: '活动结束日期',
            prop: 'endTime',
            rules: [{ required: true, message: '请选择', trigger: 'blur' }]
          }
        },
        {
          name: 'el-input',
          md: 12,
          attributes: { disabled: !this.qx(this.formData), placeholder: '请选择' },
          formItemAttributes: {
            label: '活动名称',
            prop: 'name',
            rules: [{ required: true, message: '请填写', trigger: 'blur' }]
          }
        },
        {
          name: 'el-input',
          md: 12,
          attributes: { disabled: !this.qx(this.formData), placeholder: '请选择', maxlength: 8 },
          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
            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.qx(this.formData)} value={value} onInput={onInput}>
                    <el-radio disabled={!this.qx(this.formData)} label={0}>
                      不限制
                    </el-radio>
                    <el-radio disabled={!this.qx(this.formData)} label={1}>
                      限制
                      {value
                        ? [
                            <el-input
                              disabled={!this.qx(this.formData)}
                              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.qx(this.formData)}
                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.qx(this.formData)}
                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.qx(this.formData)} 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.qx(this.formData),
                isAdd: this.qx(this.formData),
                isDel: this.qx(this.formData)
              },
              {
                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.qx(this.formData) ? (
                    <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 style="display: flex">
                                    {row.answer.map(item => {
                                      return (
                                        <div style="margin-right:10px">
                                          <el-radio disabled label="">
                                            {item.option_value}
                                          </el-radio>
                                          <div>
                                            {item.option_files.map(v => (
                                              <el-image
                                                src={this.$showImgUrl(v.url)}
                                                preview-src-list={[this.$showImgUrl(v.url)]}
                                                fit="fit"
                                                style="width:80px;height:80px;"
                                              />
                                            ))}
                                          </div>
                                        </div>
                                      )
                                    })}
                                  </div>,
                                  <div style="display: flex">
                                    {row.answer.map(item => {
                                      return (
                                        <div style="margin-right:10px">
                                          <el-checkbox disabled label="">
                                            {item.option_value}
                                          </el-checkbox>
                                          <div>
                                            {item.option_files.map(v => (
                                              <el-image
                                                src={this.$showImgUrl(v.url)}
                                                preview-src-list={[this.$showImgUrl(v.url)]}
                                                fit="fit"
                                                style="width:80px;height:80px;"
                                              />
                                            ))}
                                          </div>
                                        </div>
                                      )
                                    })}
                                  </div>,
                                  <div>
                                    <el-input disabled placeholder="请输入内容"></el-input>
                                  </div>,
                                  null
                                ][row.type - 1]
                              }
                            </div>
                          )
                        }
                      },
                      ...(() => {
                        if (this.qx(this.formData)) {
                          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={this.$showImgUrl(url)}
                        preview-src-list={[this.$showImgUrl(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 && 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 && 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
              })
            })
          }
        },
        edit: {
          conditions: ({ row, index, column }) => {
            return !!~[0, 1].indexOf(row.status) || !!~['待生效', '生效中'].indexOf(row.statusText)
          },
          click: ({ row, index, column }) => {
            this.typeView = 1
            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
              })
            })
          }
        },
        createActivity: {
          conditions: ({ row, index, column }) => {
            return !!~[0, 1].indexOf(row.status) || !!~['待生效', '生效中'].indexOf(row.statusText)
          },
          click: ({ row, index, column }) => {
            this.$router.push({
              name: 'activityOrder',
              params: {
                pageName: row.id,
                pageType: 'detail',
                pageCode: row.id
              }
            })
          }
        },
        viewActivity: {
          click: ({ row, index, column }) => {
            this.$router.push({
              name: 'activityOrder',
              params: {
                pageName: row.id,
                pageType: 'list',
                pageCode: row.id
              }
            })
          }
        },
        isView: {
          name: ({ row, index, column }) => {
            return row.isShow ? '隐藏' : '显示'
          },
          click: ({ row, index, column }) => {
            this.$confirm(`是否确定${row.isShow ? '隐藏' : '显示'}?`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            })
              .then(() => {
                promotionQuestionnaireShow({
                  id: row.id,
                  isShow: !row.isShow
                }).then(res => {
                  this.$message({
                    type: 'success',
                    message: `设置成功!`
                  })
                  this.$refs.pageRef.refreshList()
                })
              })
              .catch(() => {})
          }
        }
      })
    },
    // 新增
    addData() {
      this.typeView = 1
      this.formDialog = true
    },
    // 关闭弹窗
    formCancel() {
      this.typeView = 0
      this.formDialog = false
      this.$data.formData = this.$options.data().formData
    },
    // 确定
    formConfirm() {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          var data = {
            ...this.formData,
            endTime: this.formData.endTime ? `${this.formData.endTime.split(' ')[0]} 23:59:59` : '',
            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()
      this.$nextTick(() => {
        this.$refs.formRef.validateField(['promotionQuestionnaireItems'], v => {})
      })
    },
    qx(item) {
      return (
        !!this.typeView &&
        (!item.id || !!~[0, 1].indexOf(item.status) || !!~['待生效', '生效中'].indexOf(item.statusText))
      )
    },
    dqangqianyemian(...p) {
      return this.$refs.formRef.validateField(...p)
    }
  }
}
</script>

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