<template>
  <div v-if="pageLoading" class="resi-container">
    <el-card ref="searchCard" class="search-card">
      <div class="">
        <el-form ref="searchForm" :inline="true" :model="searchForm" size="small" label-width="100px" class="demo-form-inline">
          <div>
            <el-form-item label="所属党组织" prop="partyOrgId">
              <!-- <el-select v-model="searchForm.partyOrgId" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="item in optionsG"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option> -->
              <!-- </el-select> -->
              <el-cascader
                v-model="partyOrgRange"
                :options="optionsG"
                :props="partyProps"
                clearable
                @change="handlePartyChange"></el-cascader>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
              <el-input v-model="searchForm.name" placeholder="请输入" class="input-width" clearable></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="searchForm.mobile" placeholder="请输入" class="input-width" clearable></el-input>
            </el-form-item>
            <el-form-item label="身份证" prop="idCard">
              <el-input v-model="searchForm.idCard" placeholder="请输入" class="input-width" clearable></el-input>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="searchForm.address" placeholder="请输入" class="input-width" clearable></el-input>
            </el-form-item>
          </div>
          <div>
            <el-form-item label="流动党员" prop="isLd">
              <el-select v-model="searchForm.isLd" filterable placeholder="请选择" clearable>
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="流动党员证号" prop="ldzh">
              <el-input v-model="searchForm.ldzh" placeholder="请输入" class="input-width" clearable></el-input>
            </el-form-item>
            <el-form-item label="职务" prop="partyZw">
              <el-select v-model="searchForm.partyZw" filterable placeholder="请选择" clearable>
                <el-option
                  v-for="item in zwList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否缴费" prop="isPay">
              <el-select v-model="searchForm.isPay" filterable placeholder="请选择" clearable>
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item label="党员中心户" prop="isDyzxh">
              <el-select v-model="searchForm.isDyzxh" filterable placeholder="请选择" clearable>
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="免学习" prop="isMxx">
            <el-select v-model="searchForm.isMxx" filterable placeholder="请选择" clearable>
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="最近一次缴费时间"
                        label-width="130px"
                        prop="startTime">
            <el-date-picker v-model="timeRangePay"
                            size="small"
                            type="daterange"
                            value-format="yyyy-MM-dd"
                            @change="handleTimeChangePay"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间">
            </el-date-picker>

          </el-form-item>
          <el-form-item label="入党时间"
                        prop="startTime">
            <el-date-picker v-model="timeRange"
                            size="small"
                            type="daterange"
                            value-format="yyyy-MM-dd"
                            @change="handleTimeChange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间">
            </el-date-picker>

          </el-form-item>
          <el-form-item>
            <el-button class="diy-button--search" size="small" @click="handleSearch">查询</el-button>
            <el-button class="diy-button--reset" size="small" @click="resetForm('searchForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="resi-card-table">
      
      <div class="resi-row-btn">
        <el-button class="diy-button--add" size="small" @click="handleAdd">新增</el-button>
        <el-button
                   class="diy-button--export"
                   size="small"
                   @click="handleExportModule('room')">下载模板</el-button>
        <el-upload
          ref="upload"
          class="upload-demo"
          action="uploadUlr"
          :limit="1"
          :accept="'.xls,.xlsx'"
          :with-credentials="true"
          :show-file-list="false"
          :auto-upload="true"
          :on-success="handleExcelSuccess"
          :before-upload="beforeExcelUpload"
          :http-request="uploadHttpRequest"
          >
          <el-button size="small" class="diy-button--delete" :loading="importLoading">{{importBtnTitle}}</el-button>
        </el-upload>
        <el-button class="diy-button--reset" size="small" :loading="exportBtn" @click="handleExport">{{ exportBtnTitle }}</el-button>
        
      </div>
      
      <el-table
        :data="tableData"
        row-key="id"
        v-loading="tableLoading"
        border
        :height="tableHeight"
        style="width: 100%"
        class="resi-table"
      >
        <el-table-column label="序号" type="index" align="center" width="50">
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名"
          align="center"
          width="100"
        />
        <el-table-column
          prop="idCard"
          label="身份证号"
          align="center"
          min-width="180"
        />
        <el-table-column
          prop="mobile"
          label="手机号"
          align="center"
          min-width="160"
        />
        <el-table-column
          prop="rdsj"
          label="入党时间"
          align="center"
          min-width="160"
        />
        <el-table-column
          prop="sszb"
          label="所属党组织"
          align="center"
          min-width="160"
        />
        <el-table-column
          prop="ldzh"
          label="流动党员证号"
          align="center"
          min-width="160"
        />
        <el-table-column
          prop="partyZw"
          label="职务"
          align="center"
          width="100"
        />
        <el-table-column
          prop="address"
          label="地址"
          align="center"
          show-overflow-tooltip
          min-width="180"
        />
        <el-table-column
          prop="isPay"
          label="是否缴费"
          align="center"
          width="100"
        />
        <el-table-column
          prop="payDate"
          label="最近一次缴费时间"
          align="center"
          min-width="160"
        />
        <el-table-column
          prop="culture"
          label="文化程度"
          align="center"
          width="100"
        />
        <el-table-column
          prop="point"
          label="量化积分"
          align="center"
          width="100"
        />
        <el-table-column
          prop="activityPoint"
          label="活跃积分"
          align="center"
          width="100"
        />
        <el-table-column
          prop="volunteerCategory"
          label="志愿者类别"
          align="center"
          width="100"
        />
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
          min-width="180"
        />
          <!-- <template slot-scope="scope">
            <div class="div-content">{{ handleFilterSpan(scope.row, item) }}</div>
          </template> -->
        <!-- </el-table-column> -->
        <el-table-column fixed="right" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button
              @click="handleLook(scope.row)"
              type="text"
              size="small"
              class="btn-color-look"
              >查看</el-button
            >
            <el-button
                @click="handleEdit(scope.row, 'edit')"
                type="text"
                size="small"
                class="btn-color-edit"
                >修改</el-button
              >
            <el-popconfirm
                title="删除之后无法恢复，确认删除？"
                @onConfirm="handleDel(scope.row)"
              >
                <el-button
                  slot="reference"
                  type="text"
                  size="small"
                  class="btn-color-del"
                  >删除</el-button
                >
              </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[20, 50, 100, 200]"
          :page-size="pageSize"
          layout="sizes, prev, pager, next, total"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      title="党员信息"
      :visible.sync="dialogVisible"
      width="60%"
      top="5vh"
      class="dialog-h"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handlerCancle"
    >
      <crate-form v-if="dialogVisible" :info="detailInfo" :partyList="optionsG" 
      :disabled="disabled"
      @saveBase="handleSearch" @cancle="handlerCancle" />
    </el-dialog>

  </div>
</template>

<script>
import axios from 'axios'
import { mapGetters } from 'vuex'
import crateForm from './crateForm.vue'
export default {
  components: {
    crateForm
  },
  data() {
    return {
      uploadUlr: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadqrcodeV2',
      importBtnTitle: '导入',
      importLoading: false,
      exportBtn: false,
      exportBtnTitle: '导出',
      tableLoading: false,
      btnLoading: false,
      uploading: false,
      disabled: false,
      pageLoading: false,
      dialogVisible: false,
      currentPage: 1,
      pageSize: 20,
      total: null,
      tableData: [],
      searchH: 0,
      unloadPencent: 0,
      addLevel: '1',
      addType: 'add',
      value: '',
      optionsEditG: [],
      optionsG: [],
      optionsC: [],
      optionsEditC: [],
      options: [
        {
          label: '是',
          value: 1
        },{
          label: '否',
          value: 2
        }
      ],
      zwList: [
        {
          label: '普通党员',
          value: '0'
        },
        {
          label: '支部书记',
          value: '1'
        },
        {
          label: '支部委员',
          value: '2'
        },
        {
          label: '党委委员',
          value: '3'
        },
      ],
      demandOptions: [],
      tableHeader: [
        {
          label: '党员姓名',
          columnName: 'name',
          align: 'center',
          width: '160',
          options: []
        }, {
          label: '所属网格',
          align: 'center',
          columnName: 'gridName',
          width: '200',
          options: []
        }, {
          label: '分类类别',
          align: 'center',
          columnName: 'categoryName',
          width: '160',
          options: []
        }, {
          label: '主要事迹',
          columnName: 'mainDeed',
          align: 'center',
          width: '',
          options: []
        }
      ],
      partyOrgRange: [],
      timeRangePay: [],
      timeRange: [],
      customerId: '',
      searchForm: {
        partyOrgId: '',
        mobile: '',
        idCard: '',
        name: '',
        address: '',
        isLd: '',
        ldzh: '',
        partyZw: '',
        isDyzxh: '',
        isMxx: '',
        culture: '',
        isPay: '',
        rdsjStartDate: '',
        rdsjEndDate: '',
        payStatrDate: '',
        payEndDate: ''
      },
      detailInfo: {},
      partyProps: {
        label: 'partyOrgName',
        value: 'id',
        checkStrictly: true 
      }
    }
  },
   computed: {
    ...mapGetters(['clientHeight', 'iframeHeight']),
    tableHeight() {
      const h = this.clientHeight - this.searchH - 280 + this.iframeHeigh
      const _h = this.clientHeight - 280 - this.searchH
      return this.$store.state.inIframe ? h : _h
    }
  },
  async created() {
    this.customerId = localStorage.getItem('customerId')
    // setTimeout(() => {
    //   this.getTableData()
    //   this.getGridList('query')
    //   this.getGridList('addorupdate')
    //   this.getCateList('query')
    //   this.getCateList('addorupdate')
    // }, 200)
    this.getTableData()
    this.getGridList('query')
      // this.getGridList('addorupdate')
      // this.getCateList('query')
      // this.getCateList('addorupdate')
    this.pageLoading = true
    
    // this.tableHeight = document.documentElement.clientHeight - this.$refs.searchCard.$el.offsetHeight - 280 + 'px'
  },
  
  mounted() {
    
    this.$nextTick(() => {
      this.searchH = this.$refs.searchCard.$el.offsetHeight
      console.log('tableHeight', this.tableHeight)
    })
    
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getTableData()
    },
    handlePartyChange(val) {
      console.log('val------pp', val)
      this.searchForm.partyOrgId = val[val.length - 1]
    },
    handleFilterSpan(row, item) {
      let _val = ''
      if (item.options && item.options.length > 0) {
        item.options.forEach((n) => {
          if (n.value === row[item.columnName]) _val = n.label
        })
      }
      return _val || row[item.columnName]
    },
    handleTimeChange (val) {
      if (val.length > 0) {
        this.searchForm.rdsjStartDate = val[0]
        this.searchForm.rdsjEndDate = val[0]
      } else {
        this.searchForm.rdsjStartDate = ''
        this.searchForm.rdsjEndDate = ''
      }

    },
    handleTimeChangePay (val) {
      if (val.length > 0) {
        this.searchForm.payStatrDate = val[0]
        this.searchForm.payEndDate = val[1]
      } else {
        this.searchForm.payStatrDate = ''
        this.searchForm.payEndDate = ''
      }

    },
    // 上传大图标成功
    handleExcelSuccess (res, file) {
      if (res.code === 0 && res.msg === 'success') {

        console.log('resss---ppp', res)

      } else {
        this.$message.error(res.msg)
      }
    },
    handleProgress(event, file, fileList) {
      console.log('percentage', event, file.percentage)
      this.uploading = true
      this.unloadPencent = Number(file.percentage.toFixed(0))
    },
    download (data, fileName) {
      console.log('data', data)
      if (!data) {
        return
      }

      var csvData = new Blob([data])

      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(csvData, fileName)
      }
      // for Non-IE (chrome, firefox etc.)
      else {
        var a = document.createElement('a')
        document.body.appendChild(a)
        a.style = 'display: none'
        var url = window.URL.createObjectURL(csvData)
        a.href = url
        a.download = fileName
        a.click()
        a.remove()
        window.URL.revokeObjectURL(url)
      }
    },
    async handleExportModule () {
      let url = "/resi/partymember/icPartyMember/downloadTemplate"
      

      let params = {}
      
      await this.$http({
        method: 'POST',
        url,
        responseType: 'blob',
        data: params
      })
        .then(res => {
          console.log('res-------dd', res)
          if (res.headers["content-disposition"]) {
            let fileName = window.decodeURI(res.headers["content-disposition"].split(";")[1].split("=")[1])
            this.download(res.data, fileName)
            
          } else this.$message.error('下载失败')
        })
        .catch(err => {
          console.log('err', err)
          return this.$message.error('网络错误')
        })
    },
    beforeExcelUpload (file) {
      console.log('file', file)
      const isType = file.type === 'application/vnd.ms-excel'
      const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const fileType = isType || isTypeComputer
      const isLt1M = (file.size / 1024 / 1024) < 10
      if(!fileType) {
          this.$message.error('上传文件只能是xls/xlsx格式！')
      }
      
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      return fileType && isLt1M
    },
    async uploadHttpRequest(file) {
      this.importLoading = true
      this.importBtnTitle = '正在上传中...'
      this.$message({
        showClose: true,
        message: '导入中，请到系统管理-导入记录中查看进度',
        duration: 0
      })
      const formData = new FormData() //FormData对象，添加参数只能通过append('key', value)的形式添加
      formData.append('file', file.file) //添加文件对象
      this.$http
        .post('/resi/partymember/icPartyMember/import', formData).then(res => {
          console.log('res-up', res)
          if (res.data.code == 0 && res.data.msg == 'success') {
            // this.$message.success('导入成功')
            this.getTableData()
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
          console.log('失败', err)
          file.onError() //上传失败的文件会从文件列表中删除
          // this.$message.error('导入失败')
        })
      
      this.importLoading = false
      this.importBtnTitle = '导入'
      this.$refs.upload.clearFiles()
    },
    async handleExport() {
      this.exportBtn = true
      this.exportBtnTitle = '正在导出...'
      let params = {
        agencyId: this.$store.state.user.agencyId,
        pageSize: 9999,
        pageNo: this.currentPage
      }
      // .post('epmetuser/icresiuser/exportExcel', params)
      await axios({
        url: window.SITE_CONFIG['apiURL'] + '/resi/partymember/icPartyMember/export',
        // url: 'epmetuser/icresiuser/exportExcel',
        method: 'post',
        data: params,
        responseType: 'blob'
      })
        .then(res => {
          console.log('resllll', res)
          let fileName = window.decodeURI(res.headers["content-disposition"].split(";")[1].split("=")[1])
          console.log('filename', fileName)
          let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
          var url = window.URL.createObjectURL(blob)
          var aLink = document.createElement('a')
          aLink.style.display = 'none'
          aLink.href = url
          aLink.setAttribute('download', fileName)
          document.body.appendChild(aLink)
          aLink.click()
          document.body.removeChild(aLink) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        })
        .catch((err) => {
          console.log('获取导出情失败', err)
          this.$message.error('获取导出失败')
        })
        this.exportBtn = false
        this.exportBtnTitle = '导出'
    },
    beforeImgUpload (file) {
      const isPNG = (file.type === 'image/png') || (file.type === 'image/jpeg')
      const isLt1M = file.size / 1024 / 1024 < 10

      if (!isPNG) {
        this.$message.error('上传图片只能是 PNG 或 JPEG 格式!')
      }
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      return isPNG && isLt1M
    },
    handleImgSuccess (res, file) {
      if (res.code === 0 && res.msg === 'success') {

        console.log('res.data.url', res.data.url)
        this.uploading = false
        this.unloadPencent = 0
        this.form.imageList.push(res.data.url)

      } else {
        this.$message.error(res.msg)
      }
    },
    handleDelimg(item, index) {
      this.form.imageList.splice(index, 1)
    },
    handleSearch(val) {
      console.log('searchhh--', val)
      this.currentPage = 1
      this.getTableData()
    },
    resetForm(formName) {
      this.timeRangePay = []
      this.timeRange = []
      this.searchForm.payStatrDate = ''
      this.searchForm.payEndDate = ''
      this.searchForm.rdsjStartDate = ''
      this.searchForm.rdsjEndDate = ''
      this.$refs[formName].resetFields()
      this.handleSearch()
    },
    handleAdd() {
      
      this.dialogVisible = true
    },

    handlerCancle() {
      this.detailInfo = {}
      this.disabled = false
      this.dialogVisible = false
    },
    async handleLook(row) {
      this.disabled = true
      await this.getDetail(row.id)
    },
    async handleEdit(row, addType) {
      // this.form = { ...row }
      await this.getDetail(row.id)
      this.dialogVisible = true
    },
    
    handleDel(row) {
      let params = {
        ids: [row.id]
      }
      console.log('row1', row)
      this.$http
        .post('/resi/partymember/icPartyMember/delete', [row.id])
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.$message.success('删除成功')
            this.getTableData()
          }
        })
        .catch((err) => {
          return this.$message.error('网络错误')
        })
    },
    async getDetail(id) {
      let params = {
        id,
      }
      this.$http
        .post(`/resi/partymember/icPartyMember/${id}`)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.detailInfo = { ...res.data }
            this.dialogVisible = true
          }
        })
        .catch((err) => {
          console.log('row4', err)
          return this.$message.error('网络错误')
        })
    },
    async getGridList(type, agencyId) {
      const { user } = await this.$store.state
      console.log('user---ppp', user)
      // addorupdate  query
      await this.$http
        .get('/resi/partymember/icPartyOrg/getTreelist', { params: {agencyId: agencyId || user.agencyId} })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取查询详情成功', res.data)
            
            this.optionsG = this.deepArrTOnull(res.data)
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    deepArrTOnull(arr) {
      let a = []
      a = arr.map(item => {
        return {
          ...item,
          children: (item.children.length > 0 && this.deepArrTOnull(item.children) )|| null
        }
      })
      return a
    },
    async getCateList(type) {
      const { user } = await this.$store.state
      console.log('user---ppp', user)
      const params = {
        customerId: this.customerId,
        type
      }
      // addorupdate  query
      await this.$http
        .post('/resi/partymember/stylecategorydict/select-list', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            console.log('获取查询详情成功', res.data)
            
            if (type === 'query') this.optionsC = res.data
            else this.optionsEditC = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    async getTableData() {
      this.tableLoading = true
      const { user } = await this.$store.state
      let params = {
        ...this.searchForm,
        agencyId: user.agencyId,
        pageNo: this.currentPage,
        pageSize: this.pageSize
      }
      await this.$http
        .post('/resi/partymember/icPartyMember/page', params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.tableData = res.data.list
            this.total = res.data.total
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
      this.tableLoading = false
    }
    
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/scss/buttonstyle.scss";

.resi-container .resi-card-table {
  ::v-deep .el-table th {
    color: #fff;
    background-color: rgba(33, 149, 254, 1);
    // border-right: 1px solid rgba(33, 149, 254, 1);
  }
}
.resi-table {
  ::v-deep .el-button--text {
    text-decoration: underline;
  }
  ::v-deep .btn-color-del {
    margin-left: 10px;
    color: rgba(213, 16, 16, 1);
  }
  ::v-deep .btn-color-edit {
    color: rgba(0, 167, 169, 1);
  }
}
.form-wr {
  .input-width {
    width: 260px;

  }
  .input-width-textarea {
    width: 500px;
  }
  .imsg-list {
    display: flex;
    align-items: center;
    .imgs-item {
      position: relative;
      margin-right: 10px;
      .el-icon-delete {
        position: absolute;
        top: 0;
        right: 0;
        font-size: 18px;
        color: red;
        z-index: 3;
        cursor: pointer;
      }
    }
  }
}
.div-content {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

<style lang="scss" scoped>

.resi-row-btn {
  display: flex;
  margin-bottom: 13px;
  ::v-deep .el-button {
    // margin-left: 10px;
    border: 0;
  }
  ::v-deep .el-select {
    margin-right: 10px;
  }
  .el-button--success {
    background: rgba(34, 193, 195, 1);
  }
  .el-button {
    margin-left: 10px;
    border: 0;
  }
  .el-button--success {
    background: rgba(34, 193, 195, 1);
  }
  .el-button--warning {
    background: rgba(254, 179, 73, 1);
  }
  .el-button--danger {
    background: rgba(254, 98, 82, 1);
  }
}
.avatar-uploader {
  ::v-deep
  .el-upload {
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}
  
  

.resi-btns {
  margin-top: 20px;
  text-align: center;
}
</style>
