<template>
  <ai-detail>
    <template slot="title">
      <ai-title title="居民议事详情" isShowBack isShowBottomBorder @onBackClick="cancel(false)">
      </ai-title>
    </template>
    <template slot="content">
      <AiSidebar :tabTitle="tabList" v-model="currIndex" @change="onChange"></AiSidebar>
      <ai-card title="议题信息" v-show="currIndex === 0">
        <template #content>
          <ai-wrapper>
            <ai-info-item label="主题" :value="info.content" isLine></ai-info-item>
            <ai-info-item label="发布地区" :value="info.areaName" isLine></ai-info-item>
            <ai-info-item label="议事截止时间" :value="info.discussDeadline"></ai-info-item>
            <ai-info-item label="公示截止时间" :value="info.publicityDeadline"></ai-info-item>
            <ai-info-item label="议事类型" :value="dict.getLabel('discussType', info.type)" isLine></ai-info-item>
            <ai-info-item label="是否匿名投票" v-if="info.type === '1'" :value="info.anonymous === '1' ? '是' : '否'"></ai-info-item>
            <ai-info-item label="投票方式" v-if="info.type === '1'" :value="info.voteType === '0' ? '单选' : '多选'"></ai-info-item>
            <ai-info-item label="图片" isLine>
              <ai-uploader
                :instance="instance"
                disabled
                v-model="info.images"
                :limit="9">
              </ai-uploader>
            </ai-info-item>
          </ai-wrapper>
        </template>
      </ai-card>
      <ai-card title="意见征集" v-if="info.type === '0'" v-show="currIndex === 1">
        <template #right>
          <el-button type="primary" size="small" v-if="user.info.id === info.createUserId && info.status === '0'"  @click="isShowAdd = true">发表意见</el-button>
        </template>
        <template #content>
          <ai-table
            class="detail-table__table"
            :border="true"
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="total"
            :current.sync="search.current"
            :size.sync="search.size"
            :stripe="false"
            @getList="getList">
          </ai-table>
        </template>
      </ai-card>
      <ai-card title="投票统计" v-show="currIndex === 1 && info.type === '1'">
        <template #content>
          <h2 class="detail-title">选项</h2>
          <ai-wrapper>
            <ai-info-item :label="item.item + '：'" :value="item.content" isLine v-for="(item, index) in info.voteItems" :key="index"></ai-info-item>
          </ai-wrapper>
          <div class="chart" style="width: 800px; height: 240px; margin: 0 auto;"></div>
          <ai-table
            class="detail-table__table"
            :border="true"
            :tableData="tableData"
            :col-configs="voteColConfigs"
            :total="total"
            :current.sync="search.current"
            :size.sync="search.size"
            :stripe="false"
            @getList="getList">
          </ai-table>
        </template>
      </ai-card>
      <ai-dialog
        :visible.sync="isShowAdd"
        width="680px"
        height="580px"
        title="发表意见"
        @close="onClose"
        @onConfirm="onConfirm">
        <el-form ref="form" class="ai-form" :model="form" label-width="110px" label-position="right">
          <el-form-item label="发表意见" prop="content" style="width: 100%;" :rules="[{ required: true, message: '请发表你的观点和意见', trigger: 'blur' }]">
            <el-input size="small" type="textarea" :rows="5" show-word-limit :maxlength="140" placeholder="请发表你的观点和意见" v-model="form.content"></el-input>
          </el-form-item>
        </el-form>
      </ai-dialog>
    </template>
  </ai-detail>
</template>

<script>
  import * as echarts from 'echarts'
  import { mapState } from 'vuex'
  export default {
    name: 'Detail',

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

    data () {
      return {
        info: {},
        id: '',
        search: {
          current: 1,
          size: 10
        },
        isShowAdd: false,
        form: {
          content: ''
        },
        total: 0,
        currIndex: 0,
        tableData: [],
        colConfigs: [
          {prop: 'content', label: '发言内容', align: 'center'},
          {prop: 'suport', label: '获赞次数', align: 'center'},
          {prop: 'createTime', label: '发言时间', align: 'center'},
          {prop: 'createUserId', label: '发言身份', align: 'center', formart: v => v === this.info.createUserId ? '话事人' : '居民'}
        ],
        type: '',
        statistic: {},
        tabList: ['议题信息', '意见征集']
      }
    },

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

      voteColConfigs () {
        return [
          {prop: 'createTime', label: '投票时间', align: 'center'},
          {
            prop: 'userName',
            label: '发言人',
            align: 'center',
            render: (h, { row }) => {
              return h('span', {}, this.info.anonymous === '1' ? '居民' : `${row.userName}${row.phone ? '-' + row.phone : ''}`)
            }
          },
          {prop: 'item', label: '投票选项', align: 'center'}
        ]
      }
    },

    created () {
      this.getInfo(this.params.id)
    },

    methods: {
      onChange (e) {
        if (e === 1 && this.info.type === '1') {

          this.$nextTick(() => {
            this.initChart(this.statistic)
          })
        }
      },

      getInfo (id) {
        this.instance.post(`/app/appvillagediscuss/queryDetailById?id=${id}`).then(res => {
          if (res.code === 0) {
            this.info = res.data
            this.info.images = res.data.images ? JSON.parse(res.data.images) : []
            this.type = res.data.type
            this.getList()

            if (res.data.type === '1') {
              this.statistic = res.data.statistic
              this.tabList = ['议题信息', '投票表决']
            }
          }
        })
      },

      getList() {
        this.instance.post(`${this.type === '0' ? '/app/appvillagediscussmessage/list' : '/app/appvillagediscussvote/list'}`, null, {
          params: {
            discussId: this.params.id,
            ...this.search
          }
        }).then(res => {
          if (res.code == 0) {
            this.tableData = res.data.records
            this.total = res.data.total
          }
        })
      },

      initChart(data) {
        this.chart = echarts.init(document.querySelector('.chart'))
        const option = {
          tooltip: {},
          color: ['#2896FF', '#09DBFE', '#61FDB9', '#FFBB69', '#8429FF', '#ea7ccc'],
          legend: {
            right: '5%',
            top: 'center',
            orient: 'vertical',
            formatter: function(name) {
              let data = option.series[0].data
              let total = 0
              let tarValue = 0
              for (let i = 0, l = data.length; i < l; i++) {
                total += data[i].value
                if (data[i].name == name) {
                  tarValue = data[i].value
                }
              }
              let p = total === 0 ? 0 : (tarValue / total * 100).toFixed(0)
              return name + '：' + tarValue + '票' + ' ' + p + '%'
            }
          },
          series: [
            {
              type: 'pie',
              radius: '50%',
              data: Object.keys(data).map(v => {
                return {
                  value: data[v],
                  name: v
                }
              }),
              label : {
                normal : {
                formatter: '{b}：({d}%)',
                textStyle : {
                  fontWeight : 'normal',
                    fontSize : 15
                  }
                }
              }
            }
          ]
        }

        this.chart.setOption(option)
      },

      onConfirm () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.instance.post(`/app/appvillagediscussmessage/addOrUpdate`, {
              ...this.form,
              discussId: this.params.id,
              createUserId: this.user.info.name,
              createUserName: this.user.info.id,
              avatar: this.user.info.avatar
            }).then(res => {
              if (res.code === 0) {
                this.$message.success('添加成功')
                this.isShowAdd = false
                this.search.current = 1

                this.getList()
              }
            })
          }
        })
      },

      onClose () {
        this.form.content = ''
      },

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

<style scoped lang="scss">
  .detail-title {
    font-weight: normal;
    font-size: 16px;
    font-weight: 600;
  }
</style>
