<template>
  <div class="div_main">
    <div class="div_search">
      <el-form :inline="true"
               :model="formData"
               ref="ref_searchform"
               :label-width="'100px'">
        <div>

          <el-form-item label="单位名称"
                        prop="unitName">
            <el-input v-model="formData.unitName"
                      class="item_width_1"
                      clearable
                      size="small"
                      placeholder="请输入内容">
            </el-input>

          </el-form-item>
          <el-form-item label="服务事项"
                        prop="serviceMatter">
            <el-select class="item_width_2"
                       v-model="formData.serviceMatter"
                       placeholder="请选择"
                       size="small"
                       clearable>
              <el-option v-for="item in serviceList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>

          </el-form-item>
        </div>
        <div>
          <el-form-item label="分类"
                        prop="type">
            <el-select class="item_width_1"
                       v-model="formData.type"
                       placeholder="请选择"
                       size="small"
                       clearable>
              <el-option v-for="item in typeList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>

          </el-form-item>
          <el-form-item label="联系人"
                        prop="contact">
            <el-input v-model="formData.contact"
                      class="item_width_1"
                      size="small"
                      clearable
                      placeholder="请输入内容">
            </el-input>

          </el-form-item>

          <el-form-item label="联系电话"
                        prop="contactMobile">
            <el-input v-model="formData.contactMobile"
                      class="item_width_1"
                      size="small"
                      clearable
                      placeholder="请输入内容">
            </el-input>

          </el-form-item>

          <el-button style="margin-left:10px"
                     class="diy-button--search"
                     size="small"
                     @click="handleSearch">查询</el-button>
          <el-button style="margin-left:10px"
                     class="diy-button--reset"
                     size="small"
                     @click="resetSearch">重置</el-button>
        </div>
      </el-form>
    </div>
    <div class="div_table">
      <div class="div_btn">
        <el-button class="diy-button--add"
                   size="small"
                   @click="handleAdd">新增</el-button>
        <!-- 
        <el-upload :headers="$getElUploadHeaders()"  ref="upload"
                   :multiple='false'
                   :show-file-list='false'
                   :before-upload="beforeUpload"
                   action=""
                   accept=".xls,.xlsx"
                   :limit="1"
                   :on-exceed="handleExceed"
                   :http-request="uploadFile">
          <el-button style="margin-left:10px"
                     size="small"
                   class="diy-button--delete">导入</el-button> 

        </el-upload>
        <el-button style="float:left"
                  class="diy-button--reset"
                   size="small"
                   @click="handleExport">导出</el-button>-->

      </div>

      <el-table class="table"
                :data="tableData"
                border
                :height="tableHeight"
                v-loading="tableLoading"
                :header-cell-style="{background:'#2195FE',color:'#FFFFFF'}"
                style="width: 100%">
        <el-table-column label="序号"
                         header-align="center"
                         align="center"
                         type="index"
                         width="50"></el-table-column>

        <el-table-column prop="unitName"
                         header-align="center"
                         align="center"
                         label="单位名称"
                         min-width="100">
        </el-table-column>
        <el-table-column prop="agencyName"
                         header-align="center"
                         align="center"
                         label="所属组织"
                         min-width="100">
        </el-table-column>
        <el-table-column prop="type"
                         header-align="center"
                         align="center"
                         label="分类"
                         min-width="80">
        </el-table-column>
        <el-table-column prop="serviceMatterListShow"
                         header-align="center"
                         align="center"
                         label="服务事项"
                         show-overflow-tooltip
                         min-width="250">

          <!-- <template slot-scope="scope">
            <p style="text-align:center;margin:2px 0;"
               v-for="(item,index) in scope.row.serviceMatterList"
               :key="index">{{item}}</p>

          </template> -->
        </el-table-column>
        <el-table-column prop="contact"
                         header-align="center"
                         align="center"
                         label="联系人"
                         width="80">
        </el-table-column>
        <el-table-column prop="contactMobile"
                         header-align="center"
                         align="center"
                         label="联系电话"
                         width="120">
        </el-table-column>
        <el-table-column prop="memberCount"
                         header-align="center"
                         align="center"
                         label="在职党员数"
                         width="100">
        </el-table-column>
        <!-- <el-table-column prop="satisfaction"
                         header-align="center"
                         align="center"
                         label="群众满意度"
                         width="100">
        </el-table-column> -->
        <!-- <el-table-column prop="score"
                         header-align="center"
                         align="center"
                         label="积分"
                         width="80">
        </el-table-column> -->
        <el-table-column prop="remark"
                         header-align="center"
                         align="center"
                         label="备注"
                         show-overflow-tooltip
                         width="150">
        </el-table-column>
        <el-table-column label="操作"
                         fixed="right"
                         width="150"
                         header-align="center"
                         align="center"
                         class="operate">
          <template slot-scope="scope">

            <el-button type="text"
                       class="div-table-button--detail"
                       size="small"
                       @click="handleDetail(scope.row)">查看</el-button>
            <el-button v-if="agencyId===scope.row.agencyId"
                       type="text"
                       class="div-table-button--edit"
                       size="small"
                       @click="handleEdit(scope.row)">修改</el-button>

            <el-popover v-if="agencyId===scope.row.agencyId"
                        popper-class="btn-popper"
                        placement="bottom"
                        style="margin-left:10px"
                        width="20"
                        trigger="click">
              <div v-if="scope.row.syncType==='not_sync'"
                   class="table-more-btn">
                <el-button type="text"
                           class="div-table-button--detail"
                           size="small"
                           @click="handleSync(scope.row)">同步</el-button>
              </div>
              <div v-if="scope.row.syncType==='sync'"
                   class="table-more-btn">
                <el-button type="text"
                           class="div-table-button--detail"
                           size="small"
                           @click="handleNoSync(scope.row)">取消同步</el-button>
              </div>
              <div class="table-more-btn">
                <el-button type="text"
                           class="div-table-button--detail"
                           size="small"
                           @click="handleFinish(scope.row)">完成情况</el-button>
              </div>

              <div class="table-more-btn">
                <el-button type="text"
                           class="div-table-button--detail"
                           size="small"
                           @click="handleScore(scope.row)">积分记录</el-button>
              </div>
              <div class="table-more-btn">
                <el-button type="text"
                           class="div-table-button--delete"
                           size="small"
                           @click="handleDelete(scope.row)">删除</el-button>
              </div>

              <el-button type="text"
                         size="small"
                         class="div-table-button--more"
                         slot="reference">更多<i class="el-icon-caret-bottom"></i></el-button>
            </el-popover>

            <el-button v-else
                       type="text"
                       class="div-table-button--detail"
                       size="small"
                       @click="handleScore(scope.row)">积分记录</el-button>

          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="pageNo"
                       :page-sizes="[10, 20, 50]"
                       :page-size="pageSize"
                       layout="sizes, prev, pager, next, total"
                       :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 修改弹出框 -->
    <el-dialog :visible.sync="formShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="formTitle"
               :destroy-on-close="true"
               width="950px"
               top="5vh"
               class="dialog-h"
               @closed="editDiaClose">
      <units-form ref="ref_form"
                  :typeList="typeList"
                  @dialogCancle="addFormCancle"
                  @dialogOk="addFormOk"></units-form>
    </el-dialog>

    <el-dialog :visible.sync="detailShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="'单位详情'"
               width="950px"
               top="5vh"
               class="dialog-h"
               @closed="diaDetailClose">
      <units-detail ref="ref_detail"
                    @diaDetailClose="diaDetailClose"></units-detail>
    </el-dialog>

    <!-- 完成情况 -->
    <el-dialog :visible.sync="finishDiaShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="finishDiaTitle"
               width="950px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <finish-list ref="ref_finish"></finish-list>
    </el-dialog>

    <!-- 积分记录 -->
    <el-dialog :visible.sync="scoreDiaShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="scoreDiaTitle"
               width="1050px"
               top="5vh"
               @closed="diaClose">
      <score-record ref="ref_score"
                    :serviceType="'party_unit'"></score-record>
    </el-dialog>

  </div>
</template>

<script>

import unitsForm from './unitsForm'
import unitsDetail from './unitsDetail'
import finishList from './finishList'
import scoreRecord from '../../../components/scoreRecord.vue'

import { requestPost } from "@/js/dai/request";
import { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务

let loading // 加载动画
export default {
  data () {
    return {
      loading: false,
      total: 0,
      pageSize: 10,
      pageNo: 0,
      tableLoading: false,
      agencyId: '',

      unitList: [],//单位list
      serviceList: [],//服务list
      typeList: [],//分类list

      unitId: '',
      formData: {
        unitName: '',
        serviceMatter: '',
        type: '',
        contact: '',
        contactMobile: ''
      },

      tableData: [],

      //form相关
      formShow: false,
      formTitle: '新增单位',
      detailShow: false,

      //完成情况
      finishDiaTitle: '区域化党建单位完成情况',
      finishDiaShow: false,
      //积分记录
      scoreDiaTitle: '积分记录',
      scoreDiaShow: false,

      files: "",
      fileName: "",
      uploadUlr: window.SITE_CONFIG['apiURL'] + '/gov/org/neighborhood/import'

    }
  },
  components: {
    unitsForm, unitsDetail, finishList, scoreRecord
  },
  async created () {

  },
  async mounted () {
    //获取服务事项
    await this.loadService()

    //获取分类
    await this.loadType()

    const { user } = this.$store.state
    this.agencyId = user.agencyId

    await this.loadTable()
  },

  methods: {
    handleSearch () {
      this.loadTable()
    },

    //获取服务事项下拉框
    async loadService () {
      const url = "/heart/serviceitem/dict-list"


      let params = {
        // parentCategoryCode: '1010'
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.serviceList = data

      } else {
        this.$message.error(msg)
      }

    },
    //获取分类
    async loadType () {
      const url = "/sys/dict/data/dictlist"

      let params = {
        dictType: 'party_unit_type'
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.typeList = data

      } else {
        this.$message.error(msg)
      }

    },

    async loadTable () {
      this.tableLoading = true

      const url = "/heart/icpartyunit/list"
      // const url = "http://yapi.elinkservice.cn/mock/245/heart/icpartyunit/list"
      let params = {
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        agencyId: this.agencyId,
        ...this.formData
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.total = data.total
        data.list.forEach(element => {
          if (element.serviceMatterList.length > 0) {
            element.serviceMatterListShow = element.serviceMatterList.join(',')
          } else {
            element.serviceMatterListShow = ''
          }

        });
        this.tableData = data.list

      } else {
        this.$message.error(msg)
      }
      this.tableLoading = false
    },

    editDiaClose () {
      this.$refs.ref_form.resetData()
      this.formShow = false
    },
    diaClose () {
      this.detailShow = false
      this.finishDiaShow = false
      this.scoreDiaShow = false
    },
    diaDetailClose () {
      console.log(this.$refs.ref_detail)
      this.$refs.ref_detail.diaDestroy()
      this.detailShow = false
    },

    handleDetail (row) {
      // this.formTitle = '详情'
      this.detailShow = true
      this.$nextTick(() => {
        this.$refs.ref_detail.initForm(row)
      })
    },

    //完成情况
    handleFinish (row) {
      this.finishDiaTitle = row.unitName + '完成情况'
      this.finishDiaShow = true
      this.$nextTick(() => {
        this.$refs.ref_finish.initTable(row)
      })
    },
    //积分记录
    handleScore (row) {
      this.scoreDiaShow = true
      this.$nextTick(() => {
        this.$refs.ref_score.initForm(row.id)
      })
    },

    handleAdd () {
      this.formTitle = '新增'
      this.formShow = true
      this.$nextTick(() => {
        this.$refs.ref_form.initForm('add', null)
      })
    },

    handleEdit (row) {
      this.formTitle = '修改'
      this.formShow = true
      this.$nextTick(() => {
        this.$refs.ref_form.initForm('edit', row.id)
      })
    },

    addFormCancle () {
      this.formShow = false
    },
    addFormOk () {
      this.formShow = false
      this.loadTable()

    },

    async handleSync (row) {

      this.$confirm("确认同步到通讯录？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.syncUnit(row)
        })
        .catch(err => {
          if (err == "cancel") {

          }

        });
    },
    async handleNoSync (row) {

      this.$confirm("确认取消同步?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.noSyncUnit(row)
        })
        .catch(err => {
          if (err == "cancel") {

          }

        });
    },

    async syncUnit (row) {
      const url = "/gov/org/department/syncdept"

      let params = {
        id: row.id,
        deptName: row.unitName,
        mobile: row.contactMobile,
        personName: row.contact,
        deptType: 'party_unit',
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        if (data.type) {
          this.$message({
            type: "success",
            message: data.msg || "同步成功"
          });

          this.loadTable()
        } else {
          this.$message.error(data.msg)
        }

      } else {
        this.$message.error(msg)
      }
    },

    async noSyncUnit (row) {
      const url = "/gov/org/department/notsyncdept"
      // const url = "http://yapi.elinkservice.cn/mock/245/heart/icpartyunit/delete"

      let params = {
        id: row.id,
        deptId: row.deptId,
        deptStaffId: row.deptStaffId,
        deptType: 'party_unit',
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        if (data.type) {
          this.$message({
            type: "success",
            message: "取消同步成功"
          });
          this.loadTable()
        } else {
          this.$message.error(data.msg)
        }
      } else {
        this.$message.error(msg)
      }
    },

    async handleDelete (row) {

      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteUnit(row)
        })
        .catch(err => {
          if (err == "cancel") {

          }

        });
    },

    async deleteUnit (row) {
      const url = "/heart/icpartyunit/delete"
      // const url = "http://yapi.elinkservice.cn/mock/245/heart/icpartyunit/delete"

      let params = {
        id: row.id
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.$message({
          type: "success",
          message: "删除成功"
        });

        this.loadTable()
      } else {
        this.$message.error(msg)
      }
    },

    //重置搜索条件
    resetSearch () {
      this.formData = {
        unitName: '',
        serviceMatter: '',
        type: '',
        contact: '',
        contactMobile: ''
      }
      this.pageSize = 10
      this.pageNo = 0
      // this.loadTable()
    },

    //导出表格
    async handleExport () {
      let title = '联建单位列表'

      const url = "/heart/icpartyunit/export"
      let params = {
        agencyId: this.agencyId,
        ...this.formData
      }

      app.ajax.exportFilePost(
        url,
        params,
        (data, rspMsg) => {

          this.download(data, title + '.xls')
        },
        (rspMsg, data) => {
          this.$message.error(rspMsg);
        }
      );

    },

    // 下载文件
    download (data, fileName) {
      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);
      }

    },

    // 上传文件之前的钩子
    beforeUpload (file) {
      this.files = file;

      const isText = file.type === 'application/vnd.ms-excel'
      const isTextComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

      if (!isText && !isTextComputer) {
        this.$message.error('请选择正确格式的文件')
        return false
      } else {
        this.fileName = file.name;
        return true
      }

    },
    // 上传文件个数超过定义的数量
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，请删除后继续上传`)
    },

    async uploadFile () {
      this.loading = true

      if (this.fileName == "") {
        this.$message.warning('请选择要上传的文件！')
        return false
      }

      //清空上传列表
      this.$refs['upload'].clearFiles()

      var url = '/heart/icpartyunit/import'
      let fileFormData = new FormData();
      fileFormData.append('file', this.files);//filename是键，file是值，就是要传的文件，test.zip是要传的文件名

      const { data, code, msg } = await requestPost(url, fileFormData)
      if (code === 0) {
        this.$message({
          type: "success",
          message: "导入成功"
        });

        this.loadTable()
      } else {
        this.$message.error(msg)
      }


    },

    handleSizeChange (val) {
      this.pageSize = val
      this.pageNo = 1
      this.loadTable()
    },
    handleCurrentChange (val) {
      this.pageNo = val
      this.loadTable()
    },

    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    tableHeight () {

      return this.$store.state.inIframe ? this.clientHeight - 430 + this.iframeHeight : this.clientHeight - 430

    },

    ...mapGetters(['clientHeight', 'iframeHeight'])
  },
  watch: {

  },
  props: {

  }
}
</script>
<style lang="scss" scoped >
.div_main {
  width: 100%;
}

.div_search {
  background: #ffffff;
  border-radius: 4px;
  padding: 30px 20px 5px;
  box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
}

.item_width_1 {
  width: 260px;
}
.item_width_2 {
  width: 620px;
}

.div_table {
  background: #ffffff;
  box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  margin-top: 15px;
  padding: 23px 30px 10px;

  .table {
    margin-top: 20px;
  }
}

.el-row {
  /* margin-bottom: 20px; */
  display: flex;
  flex-wrap: wrap;
  margin-top: 10px;
  margin-right: 50px;
}
</style>
