<template>
  <el-dialog title="新增系统推送" :close-on-click-modal="false" :visible.sync="open" width="900px" append-to-body>
    <el-row :gutter="10">
      <el-col style="width: 550px">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="群体类型" prop="groupId">
            <el-select v-model="form.groupId" size="small" style="width: 100%">
              <el-option
                  v-for="dict in systemPushGroupIdList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="form.groupId === 0" :label="systemName+'号'" prop="usercode">
            <el-autocomplete
                class="inline-input"
                v-model="form.usercode"
                :fetch-suggestions="querySearch"
                placeholder="请输入内容"
                @select="handleSelect"
                style="width: 100%"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="昵称" v-if="form.groupId === 0 && userInfo.nickname">
            {{ userInfo.nickname }} 【{{ userInfo.usercode }}】
          </el-form-item>
          <el-form-item label="头像" v-if="form.groupId === 0 && userInfo.avatar">
            <image-avatar :src="userInfo.avatar"/>
          </el-form-item>
          <el-form-item label="发送类型" prop="sendTimeType">
            <el-select v-model="form.sendTimeType" size="small" style="width: 100%">
              <el-option
                  v-for="dict in systemPushSendTimeTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="发送时间" prop="sendTime" v-if="form.sendTimeType === 1">
            <el-date-picker
                :picker-options="pickerAfterOptions"
                value-format="yyyy-MM-dd HH:mm:ss"
                v-model="form.sendTime"
                type="datetime"
                placeholder="选择发送时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题"/>
          </el-form-item>
          <el-form-item label="消息类型" prop="type">
            <el-select v-model="form.type" size="small" @change="typeSelectHandle" style="width: 100%">
              <el-option
                  v-for="dict in systemPushTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="消息内容" prop="onlyText" v-if="form.type === 0">
            <el-input v-model="form.onlyText" placeholder="请输入消息内容" type="textarea" :rows="2"/>
          </el-form-item>
          <el-form-item label="文本一" prop="textText1" v-if="form.type === 1">
            <el-input v-model="form.textText1" placeholder="请输入第一段文本" type="textarea" :rows="2"/>
          </el-form-item>
          <el-form-item label="内容" prop="textContext" v-show="form.type === 1">
            <el-button size="mini" type="primary" icon="el-icon-circle-plus-outline" @click="textContextAddHandle">追加
            </el-button>
            <el-table
                :data="textContext"
                ref="textContextRef"
                style="width: 100%"
                :row-key="(row) => {return row.id}"
            >
              <el-table-column align="center" prop="n" label="字段" min-width="180">
                <template v-slot="scope">
                  <el-input v-model="scope.row.n" placeholder="字段"/>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="v" label="值" min-width="180">
                <template v-slot="scope">
                  <el-input v-model="scope.row.v" placeholder="值"/>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template v-slot="scope">
                  <el-button size="mini" type="text" @click="textContextRemoveHandle(scope.row)" icon="el-icon-delete"/>
                  <el-button size="mini" type="text" icon="el-icon-rank"/>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="文本二" prop="textText2" v-if="form.type === 1">
            <el-input v-model="form.textText2" placeholder="请输入第二段文本" type="textarea" :rows="2"/>
          </el-form-item>
          <el-form-item label="链接类型" prop="textLinkType" v-if="form.type === 1">
            <el-select v-model="form.textLinkType" size="small">
              <el-option :key="0" label="不可点击" :value="0"/>
              <el-option :key="1" label="打开H5" :value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item label="链接地址" prop="textLinkUrl" v-if="form.type === 1 && form.textLinkType === 1">
            <el-input v-model="form.textLinkUrl" placeholder="请输入链接地址" type="textarea" :rows="2"/>
          </el-form-item>

          <el-form-item label="标题类型" prop="oneImageTitleType" v-if="form.type === 2">
            <el-select v-model="form.oneImageTitleType" size="small">
              <el-option :key="2" label="普通标题" :value="2"/>
              <el-option :key="1" label="水印标题" :value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item label="图片" prop="oneImageImage" v-if="form.type === 2">
            <image-upload2 v-model="form.oneImageImage" custom-tip="建议图片比例16:9"/>
          </el-form-item>
          <el-form-item label="文本" prop="oneImageText" v-if="form.type === 2 && form.oneImageTitleType === 2">
            <el-input v-model="form.oneImageText" placeholder="请输入消息文本" type="textarea" :rows="2"/>
          </el-form-item>
          <el-form-item label="链接类型" prop="oneImageLinkType" v-if="form.type === 2">
            <el-select v-model="form.oneImageLinkType" size="small">
              <el-option :key="0" label="不可点击" :value="0"/>
              <el-option :key="1" label="打开H5" :value="1"/>
            </el-select>
          </el-form-item>
          <el-form-item label="链接地址" prop="oneImageLinkUrl" v-if="form.type === 2 && form.oneImageLinkType === 1">
            <el-input v-model="form.oneImageLinkUrl" placeholder="请输入链接地址" type="textarea" :rows="2"/>
          </el-form-item>
          <el-form-item label="内容" prop="imageContext" v-show="form.type === 3">
            <el-button size="mini" type="primary" icon="el-icon-circle-plus-outline" @click="imageContextAddHandle">新增</el-button>
            <span style="color: red">　　建议：第一张图片比例16:9，其他图片正方形。</span>
            <el-table
                :data="imageContext"
                ref="imageContextRef"
                style="width: 100%"
                :row-key="(row) => {return row.id}"
            >
              <el-table-column align="center" prop="title" label="图片标题" min-width="60" show-overflow-tooltip/>
              <el-table-column align="center" prop="image" label="图片" min-width="60">
                <template v-slot="scope">
                  <image-preview :src="scope.row.image" :width="60" :height="40"/>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="linkType" label="链接类型" min-width="60">
                <template v-slot="scope">
                  <span v-if="scope.row.linkType === 0">不可点击</span>
                  <span v-if="scope.row.linkType === 1">打开H5</span>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="linkUrl" label="链接" min-width="100" show-overflow-tooltip/>
              <el-table-column align="center" label="操作">
                <template v-slot="scope">
                  <el-button size="mini" type="text" @click="imageContextUpdateHandle(scope.row)" icon="el-icon-edit"/>
                  <el-button size="mini" type="text" @click="imageContextRemoveHandle(scope.row)" icon="el-icon-delete"/>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item label="图片" prop="onlyImage" v-if="form.type === 4">
            <image-upload2 v-model="form.onlyImage"/>
          </el-form-item>
          <el-form-item label="备注说明" prop="remark">
            <el-input v-model="form.remark" placeholder="请输入备注说明" type="textarea" :rows="2"/>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col style="width: 200px;">
        <preview-client :data="form" :textContext="textContext" :imageContext="imageContext"></preview-client>
      </el-col>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="open = false">取 消</el-button>
    </div>
    <el-dialog :title="imageTitle" :close-on-click-modal="false" :visible.sync="imageOpen" width="500px" append-to-body>
      <el-form ref="imageForm" :model="imageForm" :rules="imageRules" label-width="80px">
        <el-form-item label="图片标题" prop="title">
          <el-input v-model="imageForm.title" placeholder="请输入图片标题" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <image-upload2 v-model="imageForm.image"/>
        </el-form-item>
        <el-form-item label="链接类型" prop="linkType">
          <el-select v-model="imageForm.linkType" size="small">
            <el-option :key="0" label="不可点击" :value="0"/>
            <el-option :key="1" label="打开H5" :value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item label="链接地址" prop="linkUrl" v-if="this.imageForm.linkType === 1">
          <el-input v-model="imageForm.linkUrl" placeholder="请输入链接地址" type="textarea" :rows="2"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="imageSubmitForm">确 定</el-button>
        <el-button @click="imageOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  systemPushGroupIdList,
  systemPushLogStatus,
  systemPushSendTimeTypeList,
  systemPushStatusList,
  systemPushTypeList
} from '@/constant/statusMap'
import { getUserByUsercode, listUserByUserCode } from '@/api/cai/user'
import Sortable from 'sortablejs'
import PreviewClient from '@/components/PreviewInMobileClient/index.vue'
import {addSysPush, updateSysPush} from "@/api/cai/sysPush";

export default {
  components: {
    PreviewClient
  },
  data() {
    return {
      systemPushGroupIdList, systemPushLogStatus, systemPushSendTimeTypeList, systemPushStatusList, systemPushTypeList,
      systemName: process.env.VUE_APP_SYSTEM_HOME,
      open: false,
      form: {
        id: undefined,
        groupId: 0,
        usercode: undefined,

        onlyText: undefined,

        textText1: undefined,
        textText2: undefined,
        textLinkType: 0,
        textLinkUrl: undefined,

        oneImageTitleType:2,
        oneImageImage:undefined,
        oneImageText:undefined,
        oneImageLinkType: 0,
        oneImageLinkUrl: undefined,

        onlyImage:undefined,

        sendTimeType: 0,
        sendTime: undefined,
        title: undefined,
        type: 0,
        remark: undefined
      },
      imageForm:{
        title: undefined,
        image: undefined,
        linkType: undefined,
        linkUrl: undefined
      },
      imageOpen: false,
      imageTitle: '',
      textContext: [],
      imageContext:[],
      userInfo: {},
      // 表单校验
      rules: {
        groupId: [
          { required: true, message: '群体类型不能为空', trigger: 'blur' }
        ],
        sendTimeType: [
          { required: true, message: '发送类型不能为空', trigger: 'blur' }
        ],
        sendTime: [
          { required: true, message: '发送时间不能为空', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '消息类型不能为空', trigger: 'blur' }
        ],
        onlyText: [
          { required: true, message: '文本消息不能为空', trigger: 'blur' }
        ],
        textLinkUrl: [
          { required: true, message: '链接地址不能为空', trigger: 'blur' }
        ],
        oneImageLinkUrl: [
          { required: true, message: '链接地址不能为空', trigger: 'blur' }
        ],
        oneImageImage: [
          { required: true, message: '图片不能为空', trigger: 'blur' }
        ],
        onlyImage: [
          { required: true, message: '图片不能为空', trigger: 'blur' }
        ],
      },
      imageRules:{
        image: [
          { required: true, message: '图片不能为空', trigger: 'blur' }
        ],
        linkType: [
          { required: true, message: '链接类型不能为空', trigger: 'blur' }
        ],
        linkUrl: [
          { required: true, message: '链接不能为空', trigger: 'blur' }
        ],
      },
      buttonLoading: false,
      pickerAfterOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
    }
  },
  mounted() {
  },
  created() {
  },
  methods: {
    init(id) {
      this.form.id = id || undefined
      this.open = true
      this.$nextTick(() => {
        // this.$refs['form'].resetFields()
        this.form = {
          id: undefined,
          groupId: 0,
          usercode: undefined,

          onlyText: undefined,

          textText1: undefined,
          textText2: undefined,
          textLinkType: 0,
          textLinkUrl: undefined,

          oneImageTitleType:2,
          oneImageImage:undefined,
          oneImageText:undefined,
          oneImageLinkType: 0,
          oneImageLinkUrl: undefined,

          onlyImage:undefined,

          sendTimeType: 0,
          sendTime: undefined,
          title: undefined,
          type: 0,
          remark: undefined
        }
        this.userInfo = {}
        this.textContext = []
        this.imageContext = []
      })
    },
    rowDrop() {
      const tbody = this.$refs.textContextRef.$el.querySelector(
          ".el-table__body > tbody"
      );
      console.log(tbody)
      const _this = this
      Sortable.create(tbody, {
        animation: 180,
        delay: 0,
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.textContext.splice(oldIndex, 1)[0]
          _this.textContext.splice(newIndex, 0, currRow)
        }
      })
    },
    typeSelectHandle(value){
      if(value === 1){
        this.$nextTick(() => {
          this.rowDrop()
        })
      }
    },
    querySearch(querySearch, cb) {
      listUserByUserCode(querySearch).then(res => {
        cb(res.data.map((terminal) => {
          return {
            value: terminal,
            name: terminal
          }
        }))
      })
    },
    handleSelect(item) {
      getUserByUsercode(item.value).then(res => {
        this.userInfo = res.data
      })
    },
    textContextRemoveHandle(row) {
      const index = this.textContext.findIndex((item) => {
        return item.id === row.id
      })
      // 根据索引删除数据
      this.textContext.splice(index, 1)
    },
    imageContextAddHandle(){
      this.imageOpen = true;
      this.imageTitle = "添加多图文信息";
      this.$nextTick(() => {
        this.$refs['imageForm'].resetFields()
        this.imageForm.id = undefined
      })
    },
    imageContextRemoveHandle(row){
      const index = this.imageContext.findIndex((item) => {
        return item.id === row.id
      })
      // 根据索引删除数据
      this.imageContext.splice(index, 1)
    },
    imageContextUpdateHandle(row){
      this.imageOpen = true;
      this.imageTitle = "编辑多图文信息";
      this.$nextTick(() => {
        this.$refs['imageForm'].resetFields()
        let copy = {}
        Object.assign(copy,row)
        this.imageForm = copy;
      })
    },
    imageSubmitForm(){
      this.$refs["imageForm"].validate(valid => {
        if (valid) {
          if (this.imageForm.id != null) {
            const index = this.imageContext.findIndex((item) => {
              return item.id === this.imageForm.id
            })
            this.imageContext[index].image = this.imageForm.image
            this.imageContext[index].title = this.imageForm.title
            this.imageContext[index].linkType = this.imageForm.linkType
            this.imageContext[index].linkUrl = this.imageForm.linkUrl
            this.imageOpen = false
            console.log(this.imageContext)
          } else {
            this.imageContext.push({
              id: this.genNonDuplicateID(),
              image: this.imageForm.image,
              linkType: this.imageForm.linkType,
              linkUrl: this.imageForm.linkUrl,
              title: this.imageForm.title
            })
            this.imageOpen = false
            console.log(this.imageContext)
          }
        }
      });
    },
    textContextAddHandle() {
      let b = false;
      if(this.textContext.length === 0){
        b = true;
      }
      this.textContext.push({
        id: this.genNonDuplicateID(),
        n: undefined,
        v: undefined
      })
      if(b){
        this.rowDrop()
      }
    },
    /**
     * 生成一个用不重复的ID
     */
    genNonDuplicateID(randomLength) {
      if (randomLength) {
        randomLength = 8
      }
      return Number(Math.random().toString().substr(3, randomLength) + Date.now()).toString(36)
    },
    // 表单提交
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.id != null) {
            updateSysPush(this.form).then(data => {
              this.$modal.msgSuccess('修改成功')
              this.$modal.buttonLoading = false
              this.open = false
              this.$emit('refreshDataList')
            }).finally(() => {
              this.buttonLoading = false
            })
          } else {
            addSysPush({
              master: this.form,
              textContext: this.textContext,
              imageContext: this.imageContext
            }).then(data => {
              this.$modal.msgSuccess('新增成功')
              this.buttonLoading = false
              this.open = false
              this.$emit('refreshDataList')
            }).finally(() => {
              this.buttonLoading = false
            })
          }

        }
      })
    }
  }
}
</script>
