<template>
  <ai-detail>
    <template slot="title">
      <ai-title :title="params.id ? '编辑居民议事' : '添加居民议事'" isShowBack isShowBottomBorder @onBackClick="cancel(false)">
      </ai-title>
    </template>
    <template slot="content">
      <ai-card title="基本信息">
        <template #content>
          <el-form class="ai-form" :model="form" label-width="120px" ref="form">
            <el-form-item label="主题" style="width: 100%;" prop="content" :rules="[{required: true, message: '请输入主题', trigger: 'blur'}]">
              <el-input type="textarea" :rows="5" v-model="form.content" clearable placeholder="请输入主题..." :maxlength="500" show-word-limit></el-input>
            </el-form-item>
            <el-form-item prop="areaId" style="width: 100%;" label="发布地区" :rules="[{required: true, message: '请选择到村', trigger: 'change'}]">
              <ai-area-select @fullname="v => form.areaName = v" clearable always-show :instance="instance" v-model="form.areaId" :disabled-level="disabledLevel"></ai-area-select>
            </el-form-item>
            <el-form-item label="议事截止时间" prop="discussDeadline" :rules="[{required: true, message: '请选择议事截止时间', trigger: 'change'}]">
              <el-date-picker
                v-model="form.discussDeadline"
                type="datetime"
                style="width: 100%;"
                size="small"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择议事截止时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="公示截止时间" prop="publicityDeadline">
              <el-date-picker
                v-model="form.publicityDeadline"
                size="small"
                style="width: 100%;"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择公示截止时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="议事类型" prop="type" :rules="[{required: true, message: '请选择议事类型', trigger: 'change'}]">
              <el-radio-group v-model="form.type">
                <el-radio :label="item.dictValue" v-for="(item, index) in dict.getDict('discussType')" :key="index">{{ item.dictName }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="form.type === '1'" class="vite-form__item" style="width: 100%;" label="投票选项" prop="voteItems" :rules="[{required: true, message: '请添加投票选项', trigger: 'change'}]">
              <el-form-item style="width: 100%" label-width="80px" :label="'选项' + (index + 1)" v-for="(item, index) in form.voteItems" :key="'选项' + (index + 1)">
                <div class="form-flex">
                  <el-input show-word-limit style="width:400px"  v-model="item.content" :maxlength="200" size="small" placeholder="请输入选项"></el-input>
                  <el-button type="danger" size="small" @click="removeVote(index)">删除</el-button>
                </div>
              </el-form-item>
              <el-button type="primary" size="small" @click="addVote">添加选项</el-button>
            </el-form-item>
            <el-form-item v-if="form.type === '1'" label="是否匿名投票" prop="anonymous" :rules="[{required: true, message: '请选择是否匿名投票', trigger: 'change'}]">
              <el-switch
                v-model="form.anonymous"
                active-value="1"
                inactive-value="0">
              </el-switch>
            </el-form-item>
            <el-form-item v-if="form.type === '1'" label="投票方式" prop="voteType" :rules="[{required: true, message: '请选择投票方式', trigger: 'change'}]">
              <el-radio-group v-model="form.voteType">
                <el-radio label="0">单选</el-radio>
                <el-radio label="1">多选</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="图片" style="width: 100%;" prop="images">
              <ai-uploader
                :instance="instance"
                isShowTip
                v-model="form.images"
                :limit="9">
              </ai-uploader>
            </el-form-item>
          </el-form>
        </template>
      </ai-card>
    </template>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm" :loading="isLoading">提交</el-button>
    </template>
  </ai-detail>
</template>

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

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

    data () {
      return {
        info: {},
        form: {
          content: '',
          areaId: '',
          areaName: '',
          anonymous: '0',
          discussDeadline: '',
          publicityDeadline: '',
          type: '0',
          voteType: '0',
          voteItems: [],
          anonymity: '1',
          images: []
        },
        isLoading: false,
        keys: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
        id: ''
      }
    },

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

    created () {
      this.form.areaId = this.user.info.areaId
      this.form.areaName = this.user.info.areaName
      this.disabledLevel = this.user.info.areaList.length
      if (this.params && this.params.id) {
        this.id = this.params.id
        this.getInfo(this.params.id)
      }
    },

    methods: {
      getInfo (id) {
        this.instance.post(`/app/appvillagediscuss/queryDetailById?id=${id}`).then(res => {
          if (res.code === 0) {
            this.form = res.data
            this.form.content = res.data.title
            this.form.images = res.data.images ? JSON.parse(res.data.images) : []
          }
        })
      },

      addVote () {
        if (this.form.voteItems > 7) {
          return this.$message.error('选项不能大于7个')
        }

        this.form.voteItems.push({
          content: ''
        })
      },

      removeVote (index) {
        this.form.voteItems.splice(index, 1)
      },

      confirm () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            const endTime = new Date(this.form.discussDeadline).getTime()
            const endPublicityTime = this.form.publicityDeadline ? new Date(this.form.publicityDeadline).getTime() : 0
            const nowTime = new Date().getTime()
            if (endTime - nowTime < 0) {
              return this.$message.error('议事截止时间不能早于当前时间')
            }

            if (endPublicityTime && endPublicityTime - endTime < 0) {
              return this.$message.error('公示截止时间不能早于议事截止时间')
            }

            if (this.form.type === '1' && this.form.voteItems.length < 2) {
              return this.$message.error('投票选项不能少于2')
            }

            if (this.form.type === '1') {
              this.form.voteItems = this.form.voteItems.map((v, index) => {
                return {
                  content: v.content,
                  item: this.keys[index]
                }
              })

              for (let v of this.form.voteItems) {
                if (!v.content) {
                  return this.$message.error(`请输入选项${v.item}的内容`)
                }
              }
            }
            this.isLoading = true
            this.instance.post(`/app/appvillagediscuss/addOrUpdate`, {
              ...this.form,
              createUserId: this.user.info.id,
              createUserName: this.user.info.name,
              images: this.form.images.length ? JSON.stringify(this.form.images) : '',
            }).then(res => {
              if (res.code == 0) {
                this.$message.success('提交成功')
                setTimeout(() => {
                  this.isLoading = false
                  this.cancel(true)
                }, 300)
              }
            }).catch(() => {
              this.isLoading = false
            })
          }
        })
      },

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

<style scoped lang="scss">
    .vite-form__item {
      .form-flex {
        display: flex;
        align-items: center;

        .el-button {
          margin-left: 20px;
        }

        ::v-deep .el-form-item__content {
          margin-left: 0!important;
        }
      }
    }
</style>
