<template>
  <el-card shadow="never"
           class="aui-card--fill">
    <div class="mod-sys__deptmacode}">
      <el-form :inline="true"
               :model="dataForm"
               @keyup.enter.native="getDataList()">
        <el-form-item label="所属机构">
          <el-cascader v-model="deptIdList"
                       :options="options"
                       :props="{ checkStrictly: true }"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="小程序码类别">
          <el-select v-model="dataForm.leaderFlag"
                     placeholder="小程序码类别">
            <el-option v-for="item in maCodeCategorys"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList()">{{ $t('query') }}</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info"
                     @click="clearDataForm()">清空</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$hasPermission('sys:deptmacode:init')"
                     type="primary"
                     @click="initDeptMaCodeHandle()">初始化机构</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$hasPermission('sys:deptmacode:leader')"
                     type="primary"
                     @click="createGridLeaderMaCodeHandle()">生成网格长注册码</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="dataListLoading"
                :data="dataList"
                border
                @selection-change="dataListSelectionChangeHandle"
                style="width: 100%;">
        <el-table-column prop="allDeptNames"
                         label="所属部门"
                         header-align="center"
                         align="center"></el-table-column>
        <el-table-column align="center"
                         label="小程序码"
                         :show-overflow-tooltip="true"
                         prop="codeUrl">
          <template slot-scope="scope">
            <el-popover placement="right"
                        title=""
                        trigger="click"
                        class="big_image">
              <el-image slot="reference"
                        min-width="70"
                        height="70"
                        v-if="scope.row.codeUrl"
                        :src="scope.row.codeUrl"
                        :alt="scope.row.codeUrl"></el-image>
              <img class="big_image"
                   :src="scope.row.codeUrl" />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime"
                         label="创建时间"
                         header-align="center"
                         align="center"></el-table-column>
        <el-table-column :label="$t('handle')"
                         fixed="right"
                         header-align="center"
                         width="300"
                         align="center">
          <template slot-scope="scope">
            <el-button v-if="$hasPermission('sys:deptmacode:delete') && scope.row.codeUrl && scope.row.leaderFlag === '0'"
                       type="danger"
                       size="mini"
                       @click="deleteHandle(scope.row.id)">{{ $t('delete') }}</el-button>
            <el-button v-if="scope.row.codeUrl"
                       type="danger"
                       size="mini"
                       @click="downloadHandle(scope.row.codeUrl)">下载</el-button>
            <el-button v-if="$hasPermission('sys:deptmacode:create') && !scope.row.codeUrl"
                       type="primary"
                       size="mini"
                       @click="createDeptMaCodeHandle(scope.row.gridId)">生成</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="page"
                     :page-sizes="[10, 20, 50, 100]"
                     :page-size="limit"
                     :total="total"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="pageSizeChangeHandle"
                     @current-change="pageCurrentChangeHandle">
      </el-pagination>
      <epidemicSentryPost v-if="epidemicSentryPostVisible"
                          ref="epidemicSentryPost"
                          @refreshDataList="getDataList"></epidemicSentryPost>
    </div>
  </el-card>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import epidemicSentryPost from '../custom/epidemicsentrypost'
import Cookies from 'js-cookie'
export default {
  mixins: [mixinViewModule],
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '/sys/optimize/deptmacode/page',
        getDataListIsPage: true,
        deleteURL: '/sys/optimize/deptmacode',
        deleteIsBatch: true
      },
      dataForm: {
        streetId: null,
        communityId: null,
        gridId: null,
        leaderFlag: '0'
      },
      epidemicSentryPostVisible: false,
      upLoadUrl: '',
      deptIdList: [],
      options: [],
      streetList: [],
      communityList: [],
      gridList: [],
      maCodeCategorys: [
        { id: '0', name: '群众注册码' },
        { id: '1', name: '网格长注册码' }
      ]
    }
  },
  components: {
    epidemicSentryPost
  },
  created () {
    this.uploadUrl = `${window.SITE_CONFIG['apiURL']}/custom/epidemicSentryPost/importExcel?token=${Cookies.get('token')}`
    this.$http
      .get(`/sys/user/deptOptions/getBusinessDeptByUser`)
      .then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.options = res.data.options
      })
      .catch(() => { })
  },
  watch: {
    'deptIdList': function (val) {
      if (val.length === 0) {
        this.dataForm.streetId = ''
        this.dataForm.communityId = ''
        this.dataForm.gridId = ''
      }
      if (val.length === 1) {
        this.dataForm.streetId = this.deptIdList[0]
        this.dataForm.communityId = ''
        this.dataForm.gridId = ''
      }
      if (val.length === 2) {
        this.dataForm.streetId = this.deptIdList[0]
        this.dataForm.communityId = this.deptIdList[1]
        this.dataForm.gridId = ''
      }
      if (val.length === 3) {
        this.dataForm.streetId = this.deptIdList[0]
        this.dataForm.communityId = this.deptIdList[1]
        this.dataForm.gridId = this.deptIdList[2]
      }
    }
  },
  methods: {
    createDeptMaCodeHandle (id) {
      this.$confirm(
        this.$t('prompt.info', { handle: '生成小程序码' }),
        this.$t('生成'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          this.$http
            .post(`/sys/optimize/deptmacode/create/${id}`)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message({
                message: this.$t('prompt.success'),
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.getDataList()
                }
              })
            })
            .catch(() => { })
        })
        .catch(() => { })
    },
    createGridLeaderMaCodeHandle () {
      this.$confirm(
        this.$t('prompt.info', { handle: '生成网格长注册小程序码' }),
        this.$t('生成'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      )
        .then(() => {
          this.$http
            .post(`/sys/optimize/deptmacode/gridLeader`)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message({
                message: this.$t('prompt.success'),
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.getDataList()
                }
              })
            })
            .catch(() => { })
        })
        .catch(() => { })
    },
    initDeptMaCodeHandle () {
      this.$confirm('加载全部网格，加载完成后可在操作栏生成小程序码', this.$t('初始化'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      })
        .then(() => {
          let loading = this.$loading({
            lock: true,
            text: '正在进行初始化...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.$http
            .post(`/sys/optimize/deptmacode/initDeptForMaCode`)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              loading.close()
              this.$message({
                message: this.$t('prompt.success'),
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.getDataList()
                }
              })
            })
            .catch(() => { })
        })
        .catch(() => { })
    },
    clearDataForm () {
      this.dataForm.streetId = this.dataForm.communityId = this.dataForm.gridId = null
      this.communityList = this.gridList = []
    },
    downloadHandle (codeUrl) {
      window.location.href = `${window.SITE_CONFIG['apiURL']}/oss/file/download?fileUrl=${codeUrl}`
    },
    // 哨卡管理
    sentryManage (id) {
      this.epidemicSentryPostVisible = true
      this.$nextTick(() => {
        this.$refs.epidemicSentryPost.dataForm.gridId = id
        this.$refs.epidemicSentryPost.init()
      })
    },
    uploadSuccess (response, file, fileList) {
      this.$refs.upload.clearFiles()
      if (response.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.$message({
        message: this.$t('prompt.success'),
        type: 'success',
        duration: 500,
        onClose: () => {
        }
      })
    },
    errorExceed (file, fileList) {
      this.$message.error('上传失败请重试')
    }
  }
}
</script>
<style scoped>
.big_image {
  width: 300px;
  height: 300px;
}
</style>
