<template>
  <ai-detail class="AppAnnounceAdd">
    <template slot="title">
      <ai-title :title="id ? '编辑居民群发' : '添加居民群发'" isShowBack isShowBottomBorder @onBackClick="cancel(false)">
      </ai-title>
    </template>
    <template slot="content">
      <div class="AppAnnounceDetail-container">
        <el-form ref="form" class="left" :model="form" label-width="110px" label-position="right">
          <ai-card title="基本信息">
            <template #content>
              <div class="ai-form">
                <el-form-item label="任务名称" prop="taskTitle" style="width: 100%;" :rules="[{ required: true, message: '请输入任务名称', trigger: 'blur' }]">
                  <el-input size="small" placeholder="请输入任务名称" v-model="form.taskTitle" :maxlength="15" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="发送范围" style="width: 100%;" prop="sendScope" :rules="[{ required: true, message: '请选择发送范围', trigger: 'change' }]">
                  <el-radio-group v-model="form.sendScope" @change="onScopeChange">
                    <el-radio label="0">全部居民群</el-radio>
                    <el-radio label="1">按部门选择</el-radio>
                    <el-radio label="2">按网格选择</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="选择群主" v-if="form.sendScope !== '0'" prop="wxGroupsName" style="width: 100%;" :rules="[{ required: true, message: '请选择选择群主', trigger: 'change' }]">
                  <div class="AppAnnounceDetail-select">
                    <el-input size="small" class="AppAnnounceDetail-select__input" placeholder="请选择..." disabled v-model="form.wxGroupsName"></el-input>
                    <div class="select-left" v-if="form.filterCriteria.length && form.sendScope !== '2'">
                      <span v-for="(item, index) in form.filterCriteria" :key="index">
                        <ai-open-data type="departmentName" :openid="item"></ai-open-data>
                      </span>
                    </div>
                    <div class="select-left" v-if="form.filterCriteria.length && form.sendScope === '2'">
                      <span v-for="(item, index) in girdNames" :key="index">{{ item }}</span>
                    </div>
                    <i v-if="!form.filterCriteria.length">请选择</i>
                    <ai-picker
                      :instance="instance"
                      multiple
                      :ops="{label: form.sendScope === '2' ? 'girdName' : 'name'}"
                      :action="form.sendScope === '1' ? '/app/wxcp/wxdepartment/departList' : '/app/appgirdinfo/girdList'"
                      v-model="form.filterCriteria"
                      @pick="onPick"
                      @change="onSelcetChange">
                      <div class="select-right">选择</div>
                    </ai-picker>
                  </div>
                  <div class="tips">
                    <p>消息预计送达居民群数：</p>
                    <span>{{ groupLen }}</span>
                    <el-tooltip
                      placement="top"
                      content="任务开始后，3天内15分钟更新1次，3天后访问页面时触发更新，1时间最多刷新1次">
                      <i class="iconfont iconModal_Warning"></i>
                    </el-tooltip>
                  </div>
                </el-form-item>
                <el-form-item label="发送内容" prop="content" style="width: 100%;" :rules="[{ required: true, message: '请输入发送内容', trigger: 'blur' }]">
                  <el-input size="small" type="textarea" :rows="6" placeholder="请输入文本内容..." v-model="form.content"></el-input>
                  <div class="add">
                    <div class="fileList" v-if="fileList.length">
                      <div class="add-item" v-for="(item, index) in fileList" :key="index">
                        <div class="left">
                          <img :src="mapIcon(item.msgType)" />
                          <span>{{ item.mpTitle || item.name || item.linkTitle }}</span>
                        </div>
                        <i @click="removeFile(index)">删除</i>
                      </div>
                    </div>
                    <el-popover
                      placement="top"
                      width="340"
                      offset="0"
                      trigger="hover">
                      <div class="add-item" slot="reference" style="width: max-content;">
                        <img src="https://cdn.cunwuyun.cn/dvcp/announce/add.png" />
                        <span style="color: #2266FF; font-size: 12px;">添加附件类型</span>
                      </div>
                      <div class="AppAnnounceDetail-content-wrapper">
                        <el-upload
                          ref="upload"
                          multiple
                          :file-list="fileList"
                          :show-file-list="false"
                          :before-upload="v => handleChange(v, 10, '.jpg,.png,.jpeg')"
                          :limit="9"
                          action="/app/wxcp/upload/uploadFile"
                          accept=".jpg,.png,.jpeg"
                          :http-request="v => submitUpload(v, '1')">
                          <div class="content-item" trigger>
                            <img src="https://cdn.cunwuyun.cn/dvcp/announce/big-img.png" />
                            <p>图片</p>
                          </div>
                        </el-upload>
                        <el-upload
                          ref="upload"
                          multiple
                          :file-list="fileList"
                          :show-file-list="false"
                          :before-upload="v => handleChange(v, 10, '.mp4')"
                          :limit="9"
                          action="/app/wxcp/upload/uploadFile"
                          accept=".mp4"
                          :http-request="v => submitUpload(v, '2')">
                          <div class="content-item" trigger>
                            <img src="https://cdn.cunwuyun.cn/dvcp/announce/big-video.png" />
                            <p>视频</p>
                          </div>
                        </el-upload>
                        <el-upload
                          ref="upload"
                          multiple
                          :file-list="fileList"
                          :show-file-list="false"
                          :before-upload="v => handleChange(v, 10, '.zip,.rar,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt')"
                          :limit="9"
                          action="/app/wxcp/upload/uploadFile"
                          accept=".zip,.rar,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt"
                          :http-request="v => submitUpload(v, '3')">
                          <div class="content-item" trigger>
                          <img src="https://cdn.cunwuyun.cn/dvcp/announce/folder.png" />
                            <p>文件</p>
                          </div>
                        </el-upload>
                        <div class="content-item" @click="isShowAddLink = true">
                          <img src="https://cdn.cunwuyun.cn/dvcp/announce/site.png" />
                          <p>网页</p>
                        </div>
                        <div class="content-item" @click="isShowAddMiniapp = true">
                          <img src="https://cdn.cunwuyun.cn/dvcp/announce/miniapp.png" />
                          <p>小程序</p>
                        </div>
                      </div>
                    </el-popover>
                  </div>
                  <div class="tips">
                    <em>从本地上传，图片最大支持10MB，支持JPG,PNG格式；视频最大支持10MB，支持MP4格式；文件最大支持20MB</em>
                  </div>
                </el-form-item>
                <el-form-item label="宣发审批" prop="enableExamine" style="width: 100%;" :rules="[{ required: true, message: '请输入任务名称', trigger: 'blur' }]">
                  <el-switch
                    v-model="form.enableExamine"
                    active-value="1"
                    inactive-value="0"
                    active-text="开启后，创建的群发任务需要审批人进行审批">
                  </el-switch>
                </el-form-item>
                <el-form-item v-if="form.enableExamine === '1'" label="审批人员" prop="examines" style="width: 100%;" :rules="[{ required: true, message: '请选择审批人员', trigger: 'change' }]">
                  <div class="AppAnnounceDetail-select">
                    <el-input class="AppAnnounceDetail-select__input" size="small" placeholder="请选择..." v-model="form.examinesName"> </el-input>
                    <div class="select-left" v-if="form.examines.length">
                      <span v-for="(item, index) in form.examines" :key="index">
                        <ai-open-data type="userName" :openid="item.wxOpenUserId"></ai-open-data>
                      </span>
                    </div>
                    <i v-if="!form.examines.length">请选择</i>
                    <ai-user-get :instance="instance" v-model="form.examines" @change="onUserChange">
                      <div class="select-right">选择</div>
                    </ai-user-get>
                  </div>
                </el-form-item>
              </div>
            </template>
          </ai-card>
        </el-form>
        <div class="right">
          <Phone :avatar="user.info.avatar" @close="isShowPhone = false" :isShowClose="false" :content="form.content" :fileList="fileList"></Phone>
        </div>
        <ai-dialog
          :visible.sync="isShowAddLink"
          width="920px"
          title="链接消息"
          @close="onClose"
          @onConfirm="onLinkConfirm">
          <el-form ref="linkForm" :model="linkForm" label-width="110px" label-position="right">
            <div class="ai-form">
              <el-form-item label="标题" style="width: 100%;" prop="linkTitle" :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]">
                <el-input
                  size="small"
                  placeholder="请输入标题"
                  v-model="linkForm.linkTitle">
                </el-input>
              </el-form-item>
              <el-form-item label="链接" style="width: 100%;" prop="linkUrl" :rules="[{ required: true, message: '请输入链接', trigger: 'blur' }]">
                <el-input
                  size="small"
                  placeholder="请输入链接"
                  v-model="linkForm.linkUrl">
                </el-input>
              </el-form-item>
              <el-form-item label="描述" style="width: 100%;" prop="linkDesc" :rules="[{ required: true, message: '请输入描述', trigger: 'blur' }]">
                <el-input
                  size="small"
                  placeholder="请输入描述"
                  v-model="linkForm.linkDesc">
                </el-input>
              </el-form-item>
              <el-form-item label="封面图" prop="linkPicUrl" style="width: 100%;" :rules="[{ required: true, message: '请上传封面图', trigger: 'change' }]">
                <ai-uploader :instance="instance" v-model="linkForm.linkPicUrl" :limit="1"></ai-uploader>
              </el-form-item>
            </div>
          </el-form>
        </ai-dialog>
        <ai-dialog
          :visible.sync="isShowAddMiniapp"
          width="920px"
          title="小程序消息"
          @close="onClose"
          @onConfirm="onMiniAppForm">
          <el-form ref="miniAppForm" :model="miniAppForm" label-width="130px" label-position="right">
            <div class="ai-form">
              <el-form-item label="小程序appid" style="width: 100%;" prop="mpAppid" :rules="[{ required: true, message: '小程序appid', trigger: 'blur' }]">
                <el-input
                  size="small"
                  placeholder="小程序appid"
                  v-model="miniAppForm.mpAppid">
                </el-input>
              </el-form-item>
              <el-form-item label="小程序page路径" style="width: 100%;" prop="mpPage" :rules="[{ required: true, message: '请输入小程序page路径', trigger: 'blur' }]">
                <el-input
                  size="small"
                  placeholder="请输入小程序page路径"
                  v-model="miniAppForm.mpPage">
                </el-input>
              </el-form-item>
              <el-form-item label="标题" style="width: 100%;" prop="mpTitle" :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]">
                <el-input
                  size="small"
                  placeholder="请输入标题"
                  v-model="miniAppForm.mpTitle">
                </el-input>
              </el-form-item>
              <el-form-item label="封面图" prop="media" style="width: 100%;" :rules="[{ required: true, message: '请上传封面图', trigger: 'change' }]">
                <ai-uploader url="/app/wxcp/upload/uploadFile?type=image" :instance="instance" isWechat v-model="miniAppForm.media" :limit="1"></ai-uploader>
              </el-form-item>
            </div>
          </el-form>
        </ai-dialog>
        <ai-dialog
          :visible.sync="isShowDate"
          width="590px"
          title="定时发送"
          @close="onClose"
          @onConfirm="onDateForm">
          <el-form ref="dateForm" :model="dateForm" label-width="130px" label-position="right">
            <div class="ai-form">
              <el-form-item label="定时发送时间" style="width: 100%;" prop="choiceTime" :rules="[{ required: true, message: '请选择定时发送时间', trigger: 'change' }]">
                <el-date-picker
                  style="width: 100%;"
                  v-model="dateForm.choiceTime"
                  type="datetime"
                  size="small"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择定时发送时间">
                </el-date-picker>
              </el-form-item>
            </div>
          </el-form>
        </ai-dialog>
      </div>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm(0)" style="width: 120px;" v-loading="isLoading">通知成员发送</el-button>
      <el-button type="primary" @click="confirm(1)">定时发送</el-button>
    </template>
  </ai-detail>
</template>

<script>
  import Phone from './Phone'
  import { mapActions, mapState } from 'vuex'
  export default {
    name: 'Add',

    props: {
      instance: Function,
      dict: Object,
      params: Object
    },

    components: {
      Phone
    },

    data () {
      return {
        info: {},
        department: [],
        fileList: [],
        isShowAddLink: false,
        isShowAddMiniapp: false,
        isShowDate: false,
        isLoading: false,
        linkForm: {
          linkPicUrl: [],
          linkDesc: '',
          linkTitle: '',
          linkUrl: ''
        },
        dateForm: {
          choiceTime: ''
        },
        miniAppForm: {
          mpAppid: '',
          mpPage: '',
          mpTitle: '',
          media: []
        },
        form: {
          content: '',
          choiceTime: '',
          contents: [],
          enableExamine: '0',
          examines: [],
          wxGroups: [],
          wxGroupsName: '',
          sendScope: '0',
          sendType: 0,
          name: '',
          filterCriteria: [],
          taskTitle: '',
          examinesName: ''
        },
        girdNames: '',
        id: '',
        tagsList: []
      }
    },

    computed: {
      ...mapState(['user']),

      groupLen () {
        let i = 0
        this.form.wxGroups.forEach(v => {
          i = i + v.groupIds.split(',').length
        })

        return i
      }
    },

    created () {
      if (this.params && this.params.id) {
        this.id = this.params.id
        this.getInfo(this.params.id)
      } else {
        this.getWxGroups()
      }
    },

    methods: {
      ...mapActions(['initOpenData', 'transCanvas']),

      getInfo (id) {
        this.instance.post(`/app/appmasssendingtask/queryDetailById?id=${id}`).then(res => {
          if (res.code === 0) {
            this.form = {
              ...this.form,
              ...res.data,
              wxGroupsName: '1',
              filterCriteria: res.data.filterCriteria.split(',')
            }

            if (res.data.girdNames) {
              this.girdNames = res.data.girdNames
            }

            this.dateForm.choiceTime = res.data.choiceTime

            if (res.data.examines && res.data.examines.length) {
              this.form.examines = res.data.examines.map(v => {
                return {
                  ...v,
                  wxOpenUserId: v.examineUserId,
                  id: v.examineUserId
                }
              })
              this.form.examinesName = '1'
            }

            const content = res.data.contents.filter(v => v.msgType === '0')

            if (content.length) {
              this.$set(this.form, 'content', content[0].content)
            }

            this.fileList = res.data.contents.filter(v => v.msgType !== '0').map(v => {
              return {
                ...v,
                ...v.sysFile
              }
            })
          }
        })
      },

      onUserChange (e) {
        if (e.length) {
          this.form.examinesName = '1'
        } else {
          this.form.wxGroupsName = ''
        }
      },

      onScopeChange (e) {
        this.form.filterCriteria = []
        this.form.wxGroups = []
        this.girdNames = ''

        if (e === '0') {
          this.getWxGroups()
        } else {
          this.form.filterCriteria = []
        }
      },

      onPick (e) {
        if (this.form.sendScope === '2' && e.length) {
          this.girdNames = e.map(v => v.girdName)
        }
      },

      onSelcetChange (e) {
        if (e.length) {
          this.form.wxGroupsName = '1'
        } else {
          this.form.wxGroupsName = ''
        }
        this.getWxGroups()
      },

      getWxGroups () {
        this.instance.post(`/app/appmasssendingtask/queryWxGroups?sendScope=${this.form.sendScope}`, null, {
          data: {
            filterCriteria: this.form.filterCriteria.join(',')
          },
          headers: {'Content-Type': 'application/json;charset=utf-8'},
          transformRequest: [function (data) {
            return data.filterCriteria
          }]
        }).then(res => {
          if (res.code === 0) {
            this.form.wxGroups = res.data
          }
        })
      },

      onLinkConfirm () {
        this.$refs.linkForm.validate((valid) => {
          if (valid) {
            this.fileList.push({
              ...this.linkForm,
              linkPicUrl: this.linkForm.linkPicUrl[0].url,
              msgType: '4'
            })

            this.isShowAddLink = false
          }
        })
      },

      onMiniAppForm () {
        this.$refs.miniAppForm.validate((valid) => {
          if (valid) {
            this.fileList.push({
              ...this.miniAppForm,
              msgType: '5',
              ...this.miniAppForm.media[0],
              mediaId: this.miniAppForm.media[0].media.mediaId,
              sysFileId: this.miniAppForm.media[0].id
            })

            this.isShowAddMiniapp = false
          }
        })
      },

      onClose () {
        this.linkForm.linkPicUrl = []
        this.linkForm.linkDesc = ''
        this.linkForm.linkTitle = ''
        this.linkForm.linkUrl = ''
        this.miniAppForm.mpAppid = ''
        this.miniAppForm.mpPage = ''
        this.miniAppForm.mpTitle = ''
        this.dateForm.choiceTime = ''
      },

      removeFile (index) {
        this.fileList.splice(index, 1)
      },

      mapIcon (type) {
        return {
          1: 'https://cdn.cunwuyun.cn/dvcp/announce/img.png',
          2: 'https://cdn.cunwuyun.cn/dvcp/announce/video.png',
          3: 'https://cdn.cunwuyun.cn/dvcp/announce/folder.png',
          4: 'https://cdn.cunwuyun.cn/dvcp/announce/site.png',
          5: 'https://cdn.cunwuyun.cn/dvcp/announce/miniapp.png'
        }[type]
      },

      onBeforeUpload(event) {
        return this.onOverSize(event)
      },

      getExtension(name) {
        return name.substring(name.lastIndexOf('.'))
      },

      handleChange (e, size, accept) {
        const isLt10M = e.size / 1024 / 1024 < size
        const suffixName = this.getExtension(e.name)
        const suffixNameList = accept.split(',')

        if (suffixNameList.indexOf(`${suffixName.toLowerCase()}`) === -1) {
          this.$message.error(`不支持该格式`)
          return false
        }

        if (!isLt10M) {
          this.$message.error(`大小不超过${10}MB!`)
          return false
        }

        return true
      },

      submitUpload (file, type) {
        const fileType = {
          '1': 'image',
          '2': 'video',
          '3': 'file'
        }[type]
        let formData = new FormData()
        formData.append('file', file.file)
        formData.append('type', fileType)
        this.instance.post(`/app/wxcp/upload/uploadFile`, formData, {
          withCredentials: false
        }).then(res => {
          if (res.code == 0) {
            this.fileList.push({
              ...res.data.file,
              media: res.data.media,
              msgType: type,
              sysFileId: res.data.file.id,
              imgPicUrl: res.data.file.url,
              mediaId: res.data.media.mediaId
            })

            this.$message.success('上传成功')
          }
        })
      },

      onDateForm () {
        this.$refs.dateForm.validate((valid) => {
          if (valid) {
            this.confirm(1)
          }
        })
      },

      confirm (sendType) {
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (!this.form.wxGroups.length) {
              return this.$message.error('居民群数量不能为0')
            }

            if (sendType === 1 && !this.dateForm.choiceTime) {
              this.isShowDate = true
              return false
            }

            const contents = [
              {
                content: this.form.content,
                msgType: '0'
              },
              ...this.fileList
            ]

            if (sendType === 0) {
              this.isLoading = true
            }
            this.instance.post(`/app/appmasssendingtask/addOrUpdate`, {
              ...this.form,
              id: this.params.id,
              wxGroups: this.form.wxGroups,
              contents,
              sendType,
              choiceTime: this.dateForm.choiceTime,
              filterCriteria: this.form.filterCriteria.join(','),
              examines: this.form.examines.length ? this.form.examines.map(v => {
                return {
                  ...v,
                  examineUserId: v.id
                }
              }) : []
            }).then(res => {
              if (res.code == 0) {
                this.$message.success('提交成功')
                setTimeout(() => {
                  this.cancel(true)
                }, 600)
              }

              this.isLoading = false
            }).catch(() => {
              this.isLoading = false
            })
          }
        })
      },

      cancel (isRefresh) {
        this.$emit('change', {
          type: 'list',
          isRefresh: !!isRefresh
        })
      }
    }
  }
</script>

<style lang="scss">
  .AppAnnounceDetail-content-wrapper {
    display: flex;
    align-items: center;

    .content-item {
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      width: 64px;
      height: 64px;
      line-height: 1;
      margin-right: 4px;
      text-align: center;
      background: #F9F9F9;
      border-radius: 2px;
      cursor: pointer;

      &:hover {
        opacity: 0.6;
      }

      &:last-child {
        margin-right: 0;
      }

      img {
        width: 32px;
        height: 32px;
        margin-bottom: 4px;
      }

      p {
        color: #222;
        font-size: 12px;
      }
    }
  }

  .AppAnnounceAdd {
    .ai-detail__content {
      .ai-detail__content--wrapper {
        position: relative;
        max-width: 100%;
        margin: 0;
        height: 100%;
        overflow: hidden;
      }
    }

    * {
      box-sizing: border-box;
    }

    .add {
      display: flex;
      flex-direction: column;
      padding: 14px 16px;
      background: #F9F9F9;
      border-radius: 0px 0px 2px 2px;
      border: 1px solid #D0D4DC;
      border-top: none;

      .add-item {
        display: flex;
        align-items: center;
        line-height: 1;
        cursor: pointer;

        &:hover {
          opacity: 0.6;
        }

        img {
          width: 20px;
          height: 20px;
          margin-right: 2px;
        }

        span {
          color: #222;
          font-size: 14px;
        }
      }

      .fileList {
        margin-bottom: 12px;

        .add-item {
          justify-content: space-between;
          margin-bottom: 8px;

          .left {
            display: flex;
            align-items: center;
          }

          i {
            font-size: 14px;
            cursor: pointer;
            font-style: normal;
            color: red;

            &:hover {
              opacity: 0.6;
            }
          }

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }

    .AppAnnounceDetail-container {
      display: flex;
      position: relative;
      height: 100%;
      padding: 0 20px;
      overflow-y: overlay;

      .left {
        flex: 1;
        margin-right: 20px;
      }

      .right {
        position: sticky;
        top: 0;
      }

      .AppAnnounceDetail-select {
        display: flex;
        align-items: center;
        min-height: 32px;
        line-height: 1;
        background: #F5F5F5;
        border-radius: 2px;
        border: 1px solid #D0D4DC;

        & > i {
          flex: 1;
          height: 100%;
          line-height: 32px;
          padding: 0 12px;
          color: #888888;
          font-size: 14px;
          font-style: normal;
          border-right: 1px solid #D0D4DC;
          background: #fff;
        }

        .AppAnnounceDetail-select__input {
          position: absolute;
          left: 0;
          top: 0;
          z-index: -1;
          opacity: 0;
          height: 100%;
        }

        .select-right {
          height: 100%;
          padding: 0 12px;
          color: #222222;
          font-size: 12px;
          cursor: pointer;
          transition: all ease 0.3s;

          &:hover {
            opacity: 0.5;
          }
        }

        .select-left {
          display: flex;
          flex-wrap: wrap;
          flex: 1;
          padding: 5px 0 5px 12px;
          border-right: 1px solid #D0D4DC;
          background: #fff;

          span {
            height: 22px;
            line-height: 22px;
            margin: 0 4px 5px 0;
            padding: 0 8px;
            font-size: 12px;
            color: #222222;
            background: #F3F4F7;
            border-radius: 2px;
            border: 1px solid #D0D4DC;
          }
        }
      }
    }

    .tips {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #222222;

      span {
        margin: 0 3px;
        color: #2266FF;
      }

      i {
        color: #8899bb;
      }

      em {
        line-height: 20px;
        margin-top: 8px;
        color: #888888;
        font-size: 12px;
        font-style: normal;
      }
    }
  }
</style>
