<template>
  <ai-list class="form-list" isTabs style="width: 100%">
    <template slot="content">
      <ai-search-bar>
        <template #left>
          <ai-select
            v-model="search.status"
            @change="search.current = 1, getList()"
            placeholder="项目状态"
            :selectList="dict.getDict('questionnaireStatus')">
          </ai-select>
          <ai-select
            v-model="search.type"
            @change="search.current = 1, getList()"
            placeholder="项目类型"
            :selectList="dict.getDict('questionnaireType')">
          </ai-select>
        </template>
        <template #right>
          <el-input
            v-model="search.title"
            size="small"
            placeholder="请输入模板名称"
            clearable
            @keyup.enter.native="search.current = 1, getList()"
            @clear="search.current = 1, search.title = '', getList()"
            suffix-icon="iconfont iconSearch">
          </el-input>
        </template>
      </ai-search-bar>
      <div v-loading="loading">
        <div class="form-list__list">
          <div class="list-item list-add" @click="isShow = true">
            <span class="iconfont iconAdd"></span>
            <h2>新建项目</h2>
          </div>
          <div class="list-item" v-for="(item, index) in list" :key="index">
            <div>
              <div class="list-item__title">
                <h2 :style="{color: dict.getColor('questionnaireStatus', item.status)}">{{ dict.getLabel('questionnaireStatus', item.status) }}</h2>
                <span :class="'type-' + item.type">{{ dict.getLabel('questionnaireType', item.type) }}</span>
              </div>
              <p>{{ item.title }}</p>
              <div class="list-item__user">
                <ai-open-data type="departmentName" :openid="item.createUnitName"></ai-open-data>
                <ai-open-data type="userName" :openid="item.createUserName"></ai-open-data>
              </div>
            </div>
            <div class="list-item__bottom">
              <span>{{ item.dataCount }} 份数据</span>
              <i>{{ item.createTime }}</i>
            </div>
            <div class="list-item__operate">
              <el-button
                type="text"
                icon="iconfont iconshare"
                @click="showShare(item)"
                class="list-item__operate--item"
                :disabled="item.status !== '1'">
                分享
              </el-button>
              <el-button
                v-if="item.status === '1'"
                type="text"
                icon="iconfont iconunpublish"
                class="list-item__operate--item"
                @click="toStop(item.id)">
                停止
              </el-button>
              <el-button
                v-else
                @click="id = item.id, isShowAdd = true"
                type="text"
                icon="iconfont iconpublish"
                class="list-item__operate--item">
                发布
              </el-button>
              <el-button
                @click="showShare(item, true)"
                type="text"
                icon="iconfont iconpreview"
                class="list-item__operate--item">
                预览
              </el-button>
              <el-button
                :disabled="item.dataCount === 0"
                @click="exportFile(item.id, item.title)"
                type="text"
                icon="iconfont iconExported"
                class="list-item__operate--item">
                导出
              </el-button>
              <el-dropdown @command="e => handleCommand(e, item.id, item.type)">
                <el-button
                  type="text"
                  icon="iconfont iconMore"
                  class="list-item__operate--item">
                  更多
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="edit" :disabled="item.dataCount !== 0">编辑</el-dropdown-item>
                  <el-dropdown-item command="share">共享模板</el-dropdown-item>
                  <el-dropdown-item command="remove" :disabled="item.dataCount !== 0">删除</el-dropdown-item>
                  <el-dropdown-item command="statistics" :disabled="item.dataCount === 0">统计</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>
      <ai-dialog
        :visible.sync="isShow"
        width="800px"
        title="请选择新建项目类型"
        @close="currIndex = 0"
        @onConfirm="onConfirm">
        <div class="type-list">
          <div class="type-item" @click="currIndex = 0" :class="[currIndex === 0 ? 'type-item__active' : '']">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#iconwenjuandiaocha"></use>
            </svg>
            <span>问卷调查</span>
          </div>
          <div class="type-item" @click="currIndex = 1" :class="[currIndex === 1 ? 'type-item__active' : '']">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#iconkaoshiceping"></use>
            </svg>
            <span>考试测评</span>
          </div>
          <div class="type-item" @click="currIndex = 2" :class="[currIndex === 2 ? 'type-item__active' : '']">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#iconbaomingdengji"></use>
            </svg>
            <span>报名登记</span>
          </div>
          <div class="type-item" @click="currIndex = 3" :class="[currIndex === 3 ? 'type-item__active' : '']">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#iconmanyidiaocha"></use>
            </svg>
            <span>满意调查</span>
          </div>
          <div class="type-item" @click="currIndex = 4" :class="[currIndex === 4 ? 'type-item__active' : '']">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icontoupiaopingxuan"></use>
            </svg>
            <span>投票评选</span>
          </div>
        </div>
      </ai-dialog>
      <ai-dialog
        class="ai-dialog__success"
        :visible.sync="isShowSuccess"
        customFooter
        width="800px"
        title="">
        <div class="success-dialog">
          <div class="success-header">
            <i class="iconfont iconSteps_Finished"></i>
            <h2>分享表单</h2>
          </div>
          <div class="success-wrapper">
            <div class="step">
              <div class="step-left">
                <div class="stop-left__title">
                  <i></i>
                  <h2>分享方法</h2>
                </div>
                <p>可以将生成的二维码或链接分享给居民</p>
                <el-input size="small" :value="info.linkUrl">
                  <el-button slot="append" type="primary" @click="copy(info.linkUrl)">复制链接</el-button> 
                </el-input>
              </div>
              <div class="step-right">
                <div class="step-code">
                  <img :src="info.qrCodeUrl">
                </div>
                <el-button type="text" @click="downloadImg(info.qrCodeUrl)">下载二维码</el-button>
                <!-- <a download="二维码" :href="info.qrCodeUrl" target="_blank">下载二维码</a> -->
              </div>
            </div>
          </div>
        </div>
      </ai-dialog>
      <ai-dialog
        :visible.sync="isShowPreview"
        width="800px"
        customFooter
        title="预览">
        <iframe class="iframe" :src="info.linkUrl" frameborder="0"></iframe>
        <template #footer>
          <el-button @click="isShowPreview = false">关闭</el-button>
        </template>
      </ai-dialog>
      <ai-dialog
        :visible.sync="isShowAdd"
        width="800px"
        @close="onClose"
        customFooter
        title="发布">
        <el-form label-position="top" class="publish" ref="form" label-width="120px" :model="editForm">
          <div class="form-item__wrapper">
            <div class="form-title">
              <h2>基本信息</h2>
            </div>
            <div class="form-field">
              <i>*</i>
              <h2>截止时间</h2>
              <span>（表单截止后，用户打开表单会提示此表单已结束）</span>
            </div>
            <div class="form-item__container">
              <el-radio-group v-model="editForm.periodValidityType">
                <el-radio label="0">永久有效</el-radio>
                <el-radio label="1">自定义时间</el-radio>
              </el-radio-group>
            </div>
            <div class="form-item__container" v-if="editForm.periodValidityType === '1'">
              <el-date-picker
                v-model="editForm.periodValidityEndTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime"
                size="small"
                :picker-options="pickerOptions"
                placeholder="截止时间">
              </el-date-picker>
            </div>
            <div class="form-field">
              <i>*</i>
              <h2>匹配客户方式</h2>
              <span>（将参与活动的微信客户和企业微信客户匹配）</span>
            </div>
            <div class="form-item__container">
              <el-radio-group v-model="editForm.wechatId">
                <el-radio label="0">客户微信ID匹配</el-radio>
              </el-radio-group>
            </div>
          </div>
          <div class="form-item__wrapper">
            <div class="form-title">
              <h2>提交次数限制</h2>
              <span>此功能发布后不可修改</span>
            </div>
            <div class="form-field">
              <i>*</i>
              <h2>提交次数</h2>
            </div>
            <div class="form-item__container">
              <el-radio-group v-model="editForm.commitType">
                <el-radio label="0">不限次数</el-radio>
                <el-radio label="1">限提交一次</el-radio>
              </el-radio-group>
            </div>
            <!-- <div class="checkbox-wrapper">
              <div class="checkbox">
                <el-checkbox v-model="editForm.actionNotice" true-label="1" false-label="0">行为通知</el-checkbox>
                <span>（当客户点击或者发布表单时，发送表单的员工将会受到消息提醒）</span>
              </div>
              <div class="checkbox">
                <el-checkbox v-model="editForm.dynamicNotice" true-label="1" false-label="0">动态通知</el-checkbox>
                <span>（当客户点击或者发布表单时，会将客户的打开行为记录在客户动态里）</span>
              </div>
            </div> -->
          </div>
        </el-form>
        <template #footer>
          <el-button @click="isShowAdd = false">取消</el-button>
          <el-button type="primary" @click="publish">发布</el-button>
        </template>
      </ai-dialog>
    </template>
  </ai-list>
</template>

<script>
  export default {
    name: 'FormList',
    props: {
      instance: Function,
      dict: Object,
      areaId: String
    },

    data () {
      return {
        search: {
          current: 1,
          status: '',
          type: '',
          size: 1000000,
          templateType: 0,
          title: ''
        },
        pickerOptions: {
          disabledDate (time) {
            return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
          }
        },
        isShowAdd: false,
        isShowPublish: false,
        editForm: {
          commitType: '1',
          periodValidityType: '0',
          actionNotice: '1',
          dynamicNotice: '1',
          periodValidityEndTime: '',
          shareStatus: '0',
          wechatId: '0'
        },
        isShowSuccess: false,
        list: [],
        total: 0,
        isShowPreview: false,
        loading: false,
        info: {},
        currIndex: 0,
        isShow: false,
        id: ''
      }
    },

    created () {
      this.loading = true
      this.dict.load(['questionnaireStatus', 'questionnaireType', 'questionnaireFieldType']).then(() => {
        this.getList()
      })
    },

    methods: {
      onClose () {
        this.id = ''
        this.editForm.commitType = '1'
        this.editForm.periodValidityType = '0'
        this.editForm.actionNotice = '1'
        this.editForm.dynamicNotice = '1'
        this.editForm.periodValidityEndTime = ''
        this.editForm.shareStatus = '0'
        this.editForm.wechatId = '0'
      },

      getList () {
        this.instance.post(`/app/appquestionnairetemplate/list`, null, {
          params: {
            ...this.search
          }
        }).then(res => {
          if (res.code == 0) {
            this.list = res.data.records
            this.total = res.data.total

            this.$initWxOpenData()
            this.loading = false
          } else {
            this.loading = false
          }
        }).catch(() => {
          this.loading = false
        })
      },
      publish () {
        this.instance.post(`/app/appquestionnairetemplate/release`, null, {
          params: {
            ...this.editForm,
            id: this.id, 
            periodValidityEndTime: this.editForm.periodValidityType === '1' ? this.editForm.periodValidityEndTime : ''
          }
        }).then(res => {
          if (res.code == 0) {
            this.$message.success('提交成功')

            this.isShowAdd = false
            this.getList()

            // this.info = res.data

            // this.$nextTick(() => {
            //   this.isShowSuccess = true
            // })
          }
        })
      },

      downloadImg (url) {
        let image = new Image()
        image.setAttribute('crossOrigin', 'anonymous')
        image.onload = function() {
          let canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height
          let context = canvas.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)
          let url = canvas.toDataURL("image/png")
          let a = document.createElement("a")
          let event = new MouseEvent("click")
          a.download = '二维码'
          a.href = url
          a.dispatchEvent(event)
        }
        image.src = url
      },

      toStop (id) {
        this.$confirm('确定停止该表单？').then(() => {
          this.instance.post(`/app/appquestionnairetemplate/stopRelease?id=${id}`).then(res => {
            if (res.code === 0) {
              this.$message.success('停止成功!')
              this.getList()
            }
          })
        })
      },

      handleSizeChange () {
        this.$nextTick(() => {
          this.getList()
        })
      },

      handleChange () {
        this.$nextTick(() => {
          this.getList()
        })
      },

      handleCommand (e, id, type) {
        if (e === 'edit') {
          this.toEdit(id, type)
        } else if (e === 'share') {
          this.instance.post(`/app/appquestionnairetemplate/share?id=${id}`).then(res => {
            if (res.code === 0) {
              this.$message.success('共享成功!')
            }
          })
        } else if (e === 'remove') {
          this.$confirm('确定删除该数据？').then(() => {
            this.instance.post(`/app/appquestionnairetemplate/delete?id=${id}`).then(res => {
              if (res.code == 0) {
                this.$message.success('删除成功！')
                this.getList()
              }
            })
          })
        } else {
          this.$emit('change', {
            type: 'Statistics',
            params: {
              id
            }
          })
        }
      },

      exportFile (id, title) {
        this.instance.post(`/app/appquestionnairetemplate/export?id=${id}`, null, {
          responseType: 'blob'
        }).then(res => {
          const link = document.createElement('a')
          let blob = new Blob([res], {type: res.type})
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', title + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        })
      },

      showShare (info, isPreview) {
        this.loading = true
        this.info = info

        this.instance.post(`/app/appquestionnairetemplate/queryQrCode?id=${info.id}`).then(res => {
          if (res.code == 0) {
            this.info.linkUrl = res.data.linkUrl
            this.info.qrCodeUrl = res.data.qrCodeUrl

            this.$nextTick(() => {
              if (isPreview) {
                this.isShowPreview = true
                this.info.linkUrl = `${res.data.linkUrl}&preview=true#form`
              } else {
                this.isShowSuccess = true
              }
            })
          }

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

      copy (link) {
        let oInput = document.createElement('input')
        oInput.value = link
        document.body.appendChild(oInput)
        oInput.select()
        document.execCommand('Copy')
        this.$message({
          message: '已复制',
          type: 'success'
        })
        oInput.remove()
      },

      toEdit (id, type) {
        this.$emit('change', {
          type: 'add',
          params: {
            id,
            type,
            templateType: 0
          }
        })
      },

      onConfirm () {
        this.$emit('change', {
          type: 'add',
          params: {
            id: '',
            templateType: 0,
            type: this.currIndex
          }
        })
      }
    }
  }
</script>

<style scoped lang="scss">
  .form-list {
    ::v-deep .ai-list__content--right-wrapper {
      background: transparent!important;
      box-shadow: none!important;
      padding: 12px 0 12px!important;
    }

    ::v-deep.el-pager {
      li.active + li {
        border-left: 1px solid #D0D4DC;
      }
    } 

    .publish {
      .tips {
        display: flex;
        align-items: center;
        height: 36px;
        margin-bottom: 20px;
        padding: 0 12px;
        background: #E8EFFF;
        border-radius: 2px;

        i {
          margin-right: 2px;
          color: #2367ff;
          font-size: 16px;
        }

        h2 {
          font-size: 12px;
          color: #222222;
        }
      }

      .form-item__wrapper {
        padding-left: 24px;

        .checkbox {
          display: flex;
          align-items: center;
          margin-left: 9px;

          &:first-child {
            margin-bottom: 32px;
          }

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

        .form-title {
          display: flex;
          align-items: center;
          margin-bottom: 16px;

          span {
            margin-left: 16px;
            color: #888888;
            font-size: 14px;
          }

          h2 {
            position: relative;
            padding-left: 8px;
            font-size: 16px;
            font-weight: 700;
            color: #222222;

            &::after {
              position: absolute;
              left: 0;
              top: 50%;
              z-index: 1;
              width: 3px;
              height: 16px;
              background: #2266FF;
              content: ' ';
              transform: translateY(-50%);
            }
          }
        }

        .form-item__container {
          margin-left: 9px;
          margin-bottom: 24px;
        }

        .form-field {
          display: flex;
          align-items: center;
          margin-bottom: 16px;

          i {
            margin-right: 4px;
            color: #FF4466;
            font-size: 14px;
          }
          h2 {
            color: #222222;
            font-size: 14px;
          }

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

    .newPagination {
      width: 100%;
      display: flex;
      align-items: center;
      height: 64px;
      padding: 0 40px!important;

      .el-pagination {
        width: 100%;
        padding: 0;
      }
      ::v-deep .el-pager li.active {
        background-color: #fff !important;
        color: #2266FF !important;
        border-color: #2266FF;
      }

      ::v-deep .el-pager li {
        background-color: #fff;
        border: solid 1px #d0d4dc;
        margin-left: 8px;
        border-radius: 4px !important;
        line-height: 26px !important;
      }

      .paginationPre {
        display: flex;
        height: 28px;
        line-height: 1;
        font-size: 14px;
        font-weight: normal;
        align-items: center;

        .pagination-btns {
          display: flex;
          align-items: center;
          gap: 8px;
          color: #2266FF !important;

          ::v-deep span, ::v-deep div {
            font-size: 12px;
            cursor: pointer;
            color: #2266FF !important;

            &:hover {
              opacity: 0.8;
            }
          }
        }

        .paginationPre-total {
          font-size: 12px;
          color: #555;

          label {
            padding: 0 2px;
            font-weight: 700;
          }
        }

        & > * + * {
          margin-left: 24px;
        }

        ::v-deep .el-pagination button, .el-pagination span:not([class*=suffix]) {
          line-height: 1 !important;
        }

        ::v-deep.el-checkbox {
          padding-left: 14px;
          display: flex;
          align-items: center;

          .el-checkbox__input, .el-checkbox__inner {
            width: 14px;
            height: 14px;
            min-width: 0 !important;
            line-height: 1 !important;
          }

          .el-checkbox__label {
            font-size: 12px;
            color: #222222;
            height: auto !important;
            line-height: 1 !important;
            padding-left: 3px !important;
          }
        }
      }
    }

    .iframe {
      display: block;
      width: 375px;
      min-height: 450px;
      margin: 0 auto;
    }
    
    .ai-dialog__success {
      ::v-deep .ai-dialog__content {
        max-height: initial!important;
      }
    }

    .type-0 {
      color: #2266FF;
      background: rgba(34, 102, 255, 0.1);
    }

    .type-1 {
      color: rgba(34, 170, 153, 1);
      background: rgba(34, 170, 153, 0.1);
    }

    .type-2 {
      color: rgba(248, 180, 37, 1);
      background: rgba(248, 180, 37, 0.1);
    }

    .type-3 {
      color: rgba(102, 119, 187, 1);
      background: rgba(102, 119, 187, 0.1);
    }

    .type-4 {
      color: rgba(236, 68, 97, 1);
      background: rgba(236, 68, 97, 0.1);
    }

    .success-dialog {
      .success-wrapper {
        margin-top: 40px;

        .step {
          display: flex;
          align-items: center;
          justify-content: space-between;
          &:last-child {
            img {
              width: 120px;
              height: 120px;
            }

            .step-right {
              text-align: center;
              color: #2266FF;

              a {
                display: block;
                margin-top: 10px;
                color: #2266FF;
                text-align: center;
                font-size: 14px;
                text-decoration: none;

                &:hover {
                  opacity: 0.8;
                }
              }
            }

            .step-code {
              width: 130px;
              height: 130px;
              padding: 5px;
              background: #FFFFFF;
              box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.08);
              border-radius: 4px;
              border: 1px solid #E4E8EF;
            }

            ::v-deep .el-input {
              width: 418px;
              margin-top: 20px;
              margin-left: 12px;

              span {
                color: #fff;
              }

              button:hover {
                background: linear-gradient(90deg, #299FFF 0%, #0C61FF 100%);
              }
            }
          }

          .step-left {
            p {
              max-width: 348px;
              line-height: 22px;
              margin-left: 12px;
              color: #888888;
              font-size: 14px;
            }
          }

          .stop-left__title {
            display: flex;
            align-items: center;
            margin-bottom: 10px;

            h2 {
              font-size: 16px;
              color: #222222;
            }

            i {
              width: 4px;
              height: 4px;
              flex-shrink: 1;
              margin-right: 8px;
              background: #8899BB;
            }
          }
        }
      }

      .success-header {
        padding: 16px 0 40px;
        text-align: center;
        border-bottom: 1px solid #EEEEEE;

        i {
          font-size: 64px;
          color: #2DD77D;
        }

        h2 {
          margin-top: 16px;
          color: #222222;
          font-size: 20ox;
          font-weight: 600;
        }
      }
    }

    .type-list {
      display: flex;
      align-items: center;
      height: 100px;

      .type-item {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 128px;
        height: 64px;
        margin-right: 20px;
        border-radius: 2px;
        cursor: pointer;
        border: 1px solid #E4E8EF;

        svg {
          width: 24px;
          height: 24px;
          margin-right: 8px;
        }

        &.type-item__active {
          border-color: #2266FF;
        }

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

    .form-list__list {
      display: flex;
      flex-wrap: wrap;
      margin-top: 8px;

      .list-item {
        display: flex;
        position: relative;
        flex-direction: column;
        justify-content: space-between;
        margin-bottom: 12px;
        padding: 18px 16px 16px;

        &:hover {
          .list-item__operate {
            display: flex;
          }
        }

        .list-item__operate {
          display: none;
          align-items: center;
          position: absolute;
          left: 0;
          bottom: 0;
          z-index: 1;
          width: 100%;
          height: 52px;
          text-align: center;
          background: #F7F8FA;

          & > div {
            flex: 1;
          }

          ::v-deep .el-button {
            margin-left: 0;
            padding: 0;
            i {
              color: #8899BB;
              font-size: 14px;
              transition: all 0.3s;
            }

            .el-button + .el-button {
              margin-left: 0;
            }

            span {
              margin-left: 0;
              color: #555555;
              font-size: 12px;
              transition: all 0.3s;
            }

            &:hover {
              &.is-disabled {
                i {
                  color: #8899BB;
                }

                span {
                  color: #555555;
                }
              }
            }
          }

          .list-item__operate--item {
            flex: 1;

            &:hover {
              ::v-deep i, ::v-deep span {
                color: #2266FF;
              }
            }
          }
        }

        .list-item__bottom {
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: #888888;
          font-size: 12px;

          i {
            font-style: normal;
          }
        }

        p {
          line-height: 22px;
          color: #333333;
          font-size: 14px;
          font-weight: 700;
        }

        .list-item__user {
          display: flex;
          align-items: center;
          margin-top: 12px;
          color: #888888;
          font-size: 12px;
          line-height: 20px;

          & > div:first-child {
            margin-right: 8px;
          }
        }

        .list-item__title {
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin-bottom: 14px;

          h2 {
            color: #2EA222;
            font-size: 12px;
          }

          span {
            width: 64px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            border-radius: 4px;
            font-size: 12px;
          }
        }
      }

      .list-add {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        padding: 0;
        cursor: pointer;

        span {
          font-size: 32px;
          color: #8899bb;
        }

        h2 {
          color: #555555;
          font-size: 12px;
        }

        &:hover {
          opacity: 0.6;
        }
      }

      & > div {
        width: calc((100% - 60px) / 4);
        height: 196px;
        margin: 0 20px 20px 0;
        background: #FFFFFF;
        box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.05);
        border-radius: 2px;

        &:nth-of-type(4n) {
          margin-right: 0;
        }
      }
    }
  }
</style>
