<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="地址编号" prop="addrNo">
        <el-input
          v-model="queryParams.addrNo"
          placeholder="请输入地址编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址类型" prop="addrType">
        <el-select v-model="queryParams.addrType" placeholder="请选择地址类型" clearable size="small">
          <el-option
            v-for="dict in dict.type.yiqing_addr_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="属地/社区" prop="addrName">
        <el-input
          v-model="queryParams.addrName"
          placeholder="请输入属地"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="addrDetail">
        <el-input
          v-model="queryParams.addrDetail"
          placeholder="请输入地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="belongName">
        <el-input
          v-model="queryParams.belongName"
          placeholder="请输入联系人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="belongPhone">
        <el-input
          v-model="queryParams.belongPhone"
          placeholder="请输入联系电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['yiqing:addr:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
        >导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="addrList"
      row-key="addrTreeId"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="地址编号" align="center" prop="addrNo"/>
      <el-table-column label="地址类型" align="center" prop="addrType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yiqing_addr_type" :value="scope.row.addrType"/>
        </template>
      </el-table-column>
      <el-table-column label="属地/社区" align="center" prop="addrName"/>
      <el-table-column label="居委" align="center" prop="houseNo"/>
      <el-table-column label="地址" align="center" prop="addrDetail"/>
      <el-table-column label="联系人" align="center" prop="belongName"/>
      <el-table-column label="联系电话" align="center" prop="belongPhone"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['yiqing:addr:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['yiqing:addr:add']"
          >新增
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['yiqing:addr:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改属地社区登记对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级地址" prop="addrParentId">
          <treeselect v-model="form.addrParentId" :options="addrOptions" :normalizer="normalizer"
                      placeholder="请选择上级地址"/>
        </el-form-item>
        <el-form-item label="地址编号" prop="addrNo">
          <el-input v-model="form.addrNo" placeholder="请输入地址编号"/>
        </el-form-item>
        <el-form-item label="地址类型" prop="addrType">
          <el-select v-model="form.addrType" placeholder="请选择地址类型">
            <el-option
              v-for="dict in dict.type.yiqing_addr_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属地/社区" prop="addrName">
          <el-input v-model="form.addrName" placeholder="请输入属地"/>
        </el-form-item>
        <el-form-item label="居委" prop="houseNo">
          <el-input v-model="form.houseNo" placeholder="请输入居委"/>
        </el-form-item>
        <el-form-item label="地址" prop="addrDetail">
          <el-input v-model="form.addrDetail" placeholder="请输入地址"/>
        </el-form-item>
        <el-form-item label="姓名" prop="belongName">
          <el-input v-model="form.belongName" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="belongPhone">
          <el-input v-model="form.belongPhone" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog  :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancelTemplate">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { addAddr, delAddr, exportAddr, getAddr, importTemplate, listAddr, updateAddr } from '@/api/yiqing/addr'
  import Treeselect from '@riophae/vue-treeselect'
  import { getToken } from '@/utils/auth'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    name: 'Addr',
    dicts: ['yiqing_addr_type', 'yq_task_belong_level'],
    components: {
      Treeselect
    },
    data() {
      return {
        templateData: {
          addrBelongType: [
            {
              'id': '主要负责人',
              'label': '主要负责人'
            }, {
              'id': '联系人',
              'label': '联系人'
            }
          ]
        },
        // 遮罩层
        loading: false,
        // 显示搜索条件
        showSearch: true,
        exportLoading: false,
        addrList: [],
        // 属地社区登记树选项
        addrOptions: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: '',
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          // 设置上传的请求头部
          headers: { Authorization: 'Bearer ' + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + '/yiqing/addr/importData'
        },
        // 查询参数
        queryParams: {
          addrTreeId: null,
          addrParentId: null,
          ancestors: null,
          addrNo: null,
          addrType: null,
          addrName: null,
          addrDetail: null,
          addrBelongType: null,
          belongName: null,
          belongPhone: null,
          isDelete: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {}
      }
    },
    created() {
      this.getList()
    },
    methods: {
      /** 查询属地社区登记列表 */
      getList() {
        this.loading = true
        listAddr(this.queryParams).then(response => {
          this.addrList = this.handleTree(response.data, 'addrTreeId', 'addrParentId')
          this.loading = false
        })
      },
      /** 转换属地社区登记数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.addrTreeId,
          label: node.addrName,
          children: node.children
        }
      },
      /** 查询属地社区登记下拉树结构 */
      getTreeselect() {
        listAddr().then(response => {
          this.addrOptions = []
          const data = { addrTreeId: 0, addrName: '最上级', children: [] }
          data.children = this.handleTree(response.data, 'addrTreeId', 'addrParentId')
          this.addrOptions.push(data)
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          addrId: null,
          addrTreeId: null,
          addrParentId: null,
          ancestors: null,
          addrNo: null,
          addrType: null,
          addrName: null,
          addrDetail: null,
          addrBelongType: null,
          belongName: null,
          belongPhone: null,
          isDelete: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset()
        this.getTreeselect()
        if (row != null && row.addrId) {
          this.form.addrParentId = row.addrTreeId
        } else {
          this.form.addrParentId = 0
        }
        this.open = true
        this.title = '添加属地社区登记'
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        this.getTreeselect()
        if (row != null) {
          this.form.addrParentId = row.addrTreeId
        }
        getAddr(row.addrId).then(response => {
          this.form = response.data
          this.open = true
          this.title = '修改属地社区登记'
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (this.form.addrId != null) {
              updateAddr(this.form).then(response => {
                this.$modal.msgSuccess('修改成功')
                this.open = false
                this.getList()
              })
            } else {
              addAddr(this.form).then(response => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        this.$modal.confirm('是否确认删除属地社区登记编号为"' + row.addrId + '"的数据项？').then(function() {
          return delAddr(row.addrId)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams
        this.$modal.confirm('是否确认导出所有属地社区登记？').then(() => {
          this.exportLoading = true
          return exportAddr(queryParams)
        }).then(response => {
          this.$download.name(response.msg)
          this.exportLoading = false
        }).catch(() => {
        })
      },
      handleImport() {
        this.upload.title = '批量导入'
        this.upload.open = true
      },

      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false
        this.upload.isUploading = false
        this.loading = false
        this.$refs.upload.clearFiles()
        this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
        this.cancel()
        this.getList()
      },

      importTemplate() {
        importTemplate().then(response => {
          this.$download.name(response.msg)
        })
      },

      submitFileForm() {
        this.loading = true
        this.$refs.upload.submit()
      },

      cancelTemplate() {
        this.upload.open = false
        this.form.moneyType = '3'
      }
    }
  }
</script>
