<template>
  <div class="g-main">
    <div class="m-search">
      <el-form :inline="true" ref="ref_searchform" :label-width="'100px'">
        <div>
          <el-form-item label="类型">
            <el-cascader v-model="this.formData.tyep" @change="handleChangeAgency" :options="options1"
              :disabled="showdisabled" :props="{
        emitPath: false,
        multiple: false,
      }"></el-cascader>
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model.trim="formData.name" size="small" class="item_width_1" clearable placeholder="请输入">
            </el-input>
          </el-form-item>
          <el-form-item label="位置">
            <el-input v-model.trim="formData.address" size="small" class="item_width_1" clearable placeholder="请输入">
            </el-input>
          </el-form-item>
          <el-form-item label="标签">
            <el-input v-model.trim="formData.tags" size="small" class="item_width_1" clearable placeholder="请输入">
            </el-input>
          </el-form-item>

        </div>
        <div class="block">
          <div style="display: flex; justify-content: flex-end;">
            <el-button style="margin-left:10px" class="diy-button--blue" size="small"
              @click="handleSearch">查询</el-button>
            <el-button style="margin-left:10px" class="diy-button--white" size="small"
              @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <div class="m-table">
      <el-button style="" class="diy-button--add" size="small" @click="handleAdd">新增</el-button>
      <el-button style="" class="diy-button--add" size="small" @click="handleExportModule()">下载模板</el-button>
      <el-button class="diy-button--white" size="small">
        <el-upload :headers="$getElUploadHeaders()" ref="upload" class="upload-btn" action="uploadUlr" :limit="1"
          :accept="'.xls,.xlsx'" :with-credentials="true" :show-file-list="false" :auto-upload="true"
          :on-progress="handleProgress" :on-success="handleExcelSuccess" :before-upload="beforeExcelUpload"
          :http-request="uploadHttpRequest">
          导入
        </el-upload>
      </el-button>
      <el-table class="table" :data="tableData" border style="width: 100%">
        <el-table-column label="序号" header-align="center" align="center" type="index" width="80"></el-table-column>
        <el-table-column prop="agencyName" header-align="center" align="center" label="所属组织"
          :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="typeName" header-align="center" align="center" label="类型" :show-overflow-tooltip="true">
          <!-- <template slot-scope="scope">
        <span>{{ scope.row.enabled === 1 ? '关闭' : '显示' }}</span>
      </template> -->
        </el-table-column>
        <el-table-column prop="name" header-align="center" align="center" label="名称" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="address" header-align="center" align="center" label="位置" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="linkman" header-align="center" align="center" label="联系人" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="linkPhone" header-align="center" align="center" label="联系电话"
          :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="tags" header-align="center" align="center" label="标签" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="remark" header-align="center" align="center" label="备注" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="250" header-align="center" align="center" class="operate">
          <template slot-scope="scope">
            <el-button type="text" style="color:#1C6AFD;" size="small" @click="handleDetail(scope.row)">查看</el-button>
            <el-button type="text" style="color:#1C6AFD;" size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="text" style="color:#1C6AFD;" size="small" @click="handleDel(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>
      <el-dialog :visible.sync="showAdd" :close-on-click-modal="false" :close-on-press-escape="false" :title="formTitle"
        width="850px" top="10vh" class="dialog-h" @closed="showAddClose">
        <add ref="ref_form" v-if="showAdd" @showAddClose="showAddClose" />
      </el-dialog>
      <el-dialog :visible.sync="showInfo" :close-on-click-modal="false" :close-on-press-escape="false" title="查看"
        width="850px" top="10vh" class="dialog-h" @closed="showInfoClose">
        <info ref="ref_form_info" v-if="showInfo" :VolunteerList="fmData" @showInfoClose="showInfoClose" />
      </el-dialog>


    </div>
  </div>
</template>

<script>
import { requestPost, requestGet } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";
import { mapGetters } from "vuex";
import add from "./add.vue"
import info from "./info.vue"
// import edit from "./edit.vue"
// import MemberManagement from "./MemberManagement.vue"
// import process from "./process.vue"
// import Record from "./activeRecord"
// import integral from "./integral"
// //   import projectInfo from "./cpts/project-info";
import axios from "axios";

export default {
    components: { add,info},

    data() {
        return {
          options1:[
        {

            "children": [
                {
                    "pv":"1",
                    "value": "11",
                    "label": "托儿所"
                },
                {
                    "pv":"1",
                    "value": "12",
                    "label": "幼儿园"
                },
                {
                    "pv":"1",
                    "value": "13",
                    "label": "小学"
                },
                {
                    "pv":"1",
                    "value": "14",
                    "label": "中学"
                },
                {
                    "pv":"1",
                    "value": "15",
                    "label": "培训机构"
                },
                {
                    "pv":"1",
                    "value": "16",
                    "label": "其它"
                }
            ],
            "value": "1",
            "label": "教育培训"
        },
        {
            "children": [
                {
                    "pv":"2",
                    "value": "21",
                    "label": "门诊"
                },
                {
                    "pv":"2",
                    "value": "22",
                    "label": "社区医院"
                },
                {
                    "pv":"2",
                    "value": "23",
                    "label": "医院"
                },
                {
                    "pv":"2",
                    "value": "24",
                    "label": "其它"
                }
            ],
            "value": "2",
            "label": "医疗卫生"
        },
        {
            "children": [
                {
                    "pv":"3",
                    "value": "31",
                    "label": "餐饮"
                },
                {
                    "pv":"3",
                    "value": "32",
                    "label": "超市"
                },
                {
                    "pv":"3",
                    "value": "33",
                    "label": "理发"
                },
                {
                    "pv":"3",
                    "value": "34",
                    "label": "书店"
                },
                {
                    "pv":"3",
                    "value": "35",
                    "label": "便利店"
                },
                {
                    "pv":"3",
                    "value": "36",
                    "label": "市场"
                },
                {
                    "pv":"3",
                    "value": "37",
                    "label": "五金"
                },
                {
                    "pv":"3",
                    "value": "38",
                    "label": "照相"
                },
                {
                    "pv":"3",
                    "value": "39",
                    "label": "综合修理"
                },
                {
                    "pv":"3",
                    "value": "30",
                    "label": "服务站"
                },
                {
                    "pv":"3",
                    "value": "330",
                    "label": "农贸市场"
                },
                {
                    "pv":"3",
                    "value": "331",
                    "label": "其它"
                }
            ],
            "value": "3",
            "label": "商业服务"
        },
        {
            "children": [
                 {
                    "pv":"4",
                    "value": "41",
                    "label": "电影院"
                },
                {
                    "pv":"4",
                    "value": "42",
                    "label": "歌剧院"
                },
                {
                    "pv":"4",
                    "value": "43",
                    "label": "图书馆"
                },
                {
                    "pv":"4",
                    "value": "44",
                    "label": "游泳馆"
                },
                {
                    "pv":"4",
                    "value": "45",
                    "label": "活动中心"
                },
                {
                    "pv":"4",
                    "value": "46",
                    "label": "体育馆"
                },
                {
                    "pv":"4",
                    "value": "47",
                    "label": "其它"
                }
            ],
            "value": "4",
            "label": "文化体育"
        },
        {
            "value": "5",
            "label": "其它"
        }
    ],
            formTitle:"",
            formData: {
                name:"",
                tyep:"",
                tags:"",
                address:"",
   
               
            },
            optionstype: [
                    { value: 1, label: "志愿者服务组织" },
                    { value: 2, label: "志愿者服务团队" },
                ],
            showprocess:false,
            EditList:{},
            OrganizationaltypeList:[],
            showAdd: false,
            showMember: false,
            showEdit: false,
            //   pageType: "list", // 列表list 处理dispose 详情info 议题详情issue-info
            pageNo: 1,
            pageSize: 20,
            total: 0,
            tableData: [
               
          ],
          importLoading:false,
          showInfo:false,

        };
      },
      computed: {
        maxTableHeight() {
          return this.$store.state.inIframe
            ? this.clientHeight - 400 + this.iframeHeigh
            : this.clientHeight - 400;
        },
        ...mapGetters(["clientHeight", "iframeHeight"]),
      },
      watch: {
    
      },
      mounted() {
        this.getLifeType()
        this.getTableData();
      },
      methods: {
            //获取类型
    handleChangeAgency(val) {
            console.log(val);
            this.formData.tyep = val;
       },
           // 获取生活圈类型
   async getLifeType () {
       const url = "/sys/dict/data/dictlist"
       let params = {
         dictType: 'voluntary_sphereLife_type',
       }
       const { data, code, msg } = await requestPost(url, params)
       if (code === 0) {
         this.OrganizationaltypeList = data;
         
       } else {
         this.$message.error(msg)
       }
     },
        //审查
        handleprocessl(row){
            this.showprocess=true
            this.EditList=row
 
        },
        //关闭审查
        
        handleprocesslClose(){
            this.showprocess=false
            this.getTableData()
        },
        //成员管理
        handleshowMember(row){

            this.showMember=true
            this.fmData=row
   
        },
        //关闭成员管理
        MemberManagementClose(){
            this.showMember=false  
            this.getTableData()
        },
        //修改
        handleEdit(row){
             this.showAdd=true
            this.formTitle="修改"

             this.$nextTick(() => {
             this.$refs.ref_form.initForm("edit", row.id);
      });
             
        },
        //关闭修改
        showEditClose(){
            this.showEdit=false
            this.getTableData()
        },
        //新增
        handleAdd(){
            this.showAdd=true
            this.formTitle="新增"
            this.$nextTick(() => {
            this.$refs.ref_form.initForm("add", null);
      });
            // this.$refs.ref_form.initForm("add", null);
        },
        //关闭新增
        showAddClose(){
            console.log("sdlkfjklsdf1");
            this.showAdd=false
            this.getTableData()
        },
        //关闭查看
        showInfoClose(){
            this.showEdit=false
        },
        //打开查看
        handleDetail(row){
          // console.log(row,"row");
          // this.showInfo=true
            this.showInfo=true
            this.formTitle="查看"
            this.$nextTick(() => {
        this.$refs.ref_form_info.initForm("info", row.id);
      });
         
  
        },
        //查询列表
        async getTableData() {
          // const url = "http://yapi.elinkservice.cn/mock/245/gov/project/project/project-list";
          const url = "/voluntary/sphereLife/list";
          let params={
              ...this.formData,
              pageNo:this.pageNo,
              pageSize: this.pageSize
          }
          const { data, code, msg } = await requestGet(url, params);
if (code === 0) {
  console.log("列表请求成功！！！！！！！！！！！！！！");
  this.total = data.total || 0;
  this.tableData = data.list;
  
  this.tableData.forEach(item => {
    this.options1.forEach(item1 => {


      if (Array.isArray(item1.children)) {
        item1.children.forEach(item2 => {
          if (item2.value.toString() == item.type) {
            item.typeName = item2.label;
          } 
        });
      } else {
      }
    });
  });

} else {
  // 错误处理逻辑
}
        },
        //模板
        async uploadHttpRequest(file) {
  
      
              // this.importLoading = true;
            console.log(this.importLoading,"this.importLoading");

              // this.importBtnTitle = '正在上传中...';
              this.$message({
                  showClose: true,
                  dangerouslyUseHTMLString: true,
                  message: "导入中，请到系统管理-<a id='clickA' style='cursor: pointer;'>导入记录</a>中查看进度",
                  duration: 3000
              });
              let than = this;
              console.log(than,"than");
              
              // document.getElementById('clickA').addEventListener('click', function () {
              //     than.$router.replace('/main/importRecord-index');
              // });
              const formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
              formData.append('file', file.file); //添加文件对象
              formData.append('code', ''); //添加文件对象
              
              console.log(formData,"formData");
              
              let url = '/voluntary/volunteerOrg/import'
              // if (this.importType == 2) {
              //   url = '/governance/icEvent/importAwo'
              // }
              console.log(url)
              await this.$http
                  .post(url, formData)
                  .then(res => {
                    log("res", res);
                      if (res.data.code == 0 && res.data.msg == 'success') {
                          const data = res.data.data;
                          this.dataList = [
                              ...Object.keys(data.option.exist).map(k => {
                                  return {
                                      index: k,
                                      srcField: data.option.exist[k],
                                      exist: true,
                                      field: data.option.exist[k]
                                  };
                              }),
                              ...Object.keys(data.option.notExist).map(k => {
                                  return {
                                      index: k,
                                      srcField: data.option.notExist[k],
                                      exist: false,
                                      field: ''
                                  };
                              })
                          ];
                          this.importOption = data.option;
                          this.importCode = data.code;
                          this.fileData = file;
                      } else this.$message.error(res.data.msg);
                  })
                  .catch(err => {
                      console.log('失败', err);
                      file.onError(); //上传失败的文件会从文件列表中删除
                  });
              this.importLoading = false;
              this.importBtnTitle = '导入';
              this.$refs.upload.clearFiles();
              this.getTableData();
          },
  
        handleExcelSuccess(res, file) {
              if (!res.code === 0 && !res.msg === 'success') {
                  this.$message.error(res.msg);
              }
        },
        beforeExcelUpload(file) {
              console.log(file,"file1");
              
              const isType = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
              
              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!');
              }
              console.log(isLt1M,"isLt1M");
              
              return fileType && isLt1M;
          },
        handleDel(row) {
          
          this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            console.log(row, "row");
          let url = "/voluntary/sphereLife/delete";
          let params = [String(row.id)];
          axios.delete(this.processUrl(url), { data: params })
            .then((res) => {
              if (res.data.code === 0) {
                this.$message.success("删除成功");
                this.getTableData();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((error) => {
              console.error("删除失败", error);
              this.$message.error("删除失败，请稍后重试");
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          })
        
        },
        diaClose(){
          this.formShow=false
        },
        resetSearch(){
          this.formData=[]
          this.getTableData()
        },

        summDetailClose(){
            this.showAdd=false
          this.getTableData()
        },
        async handleExportModule() {
          let url = "/voluntary/volunteerOrg/downloadImportTemplate";
          let params = {};
          await this.$http({
            method: "GET",
            url,
            responseType: "blob",
            data: params,
          })
            .then((res) => {
              console.log(res,"resskfk");
              
              if (res.headers["content-disposition"]) {
                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对象
              } else this.$message.error("下载失败");
            })
            .catch((err) => {
              console.log("err", err);
              return this.$message.error("网络错误");
            });
        },
     
        handleProgress(event, file, fileList) {
          console.log("percentage", file.percentage);
        },
        handleSizeChange(val) {
          console.log(`每页 ${val} 条`);
          this.pageSize = val;
          window.localStorage.setItem("pageSize", val);
          this.getTableData();
        },
        handleCurrentChange(val) {
          console.log(`当前页: ${val}`);
          this.pageNo = val;
          this.getTableData();
        },
        //查询
        handleSearch(val) {
          console.log(this.fmData);
          this.pageNo = 1;
          this.getTableData();
        },
        handleClose() {
          this.pageType = "list";
          this.currentProject = {
            projectId: "",
          };
        },
        handleEditSuccess() {
          this.handleClose();
          this.getTableData();
        },
          // 添加服务器端URL
        processUrl(url) {
          if (url.indexOf("http://") > -1 || url.indexOf("https://") > -1) {
            return url;
          }
          return process.env.VUE_APP_API_SERVER + url;
        }
      },
    };
    </script>
    
    <style lang="scss" scoped>
    @import "@/assets/scss/modules/management/list-main.scss";
    .g-main {
            width: 100%;
          }
          .m-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: 495px;
          }
          .m-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;
            }
          }
          .div_btn {
            display: flex;
            justify-content: space-between;
          }
          .el-row {
            /* margin-bottom: 20px; */
            display: flex;
            flex-wrap: wrap;
            margin-top: 10px;
            margin-right: 50px;
          }
        
    
    </style>
    