<template>
  <div class="organization">
    <el-row type="flex" class="row-bg">
      <el-col class="add-organization" >
        <i class="el-icon-circle-plus-outline" @click="dialogOrgFn()"></i>
        <i class="text" @click="dialogOrgFn()">添加机构</i>
      </el-col>
      <el-col class="add-organization" v-if="showImportFlag">
        <!--<el-upload-->
          <!--class="bg-uploader"-->
          <!--action="#"-->
          <!--:show-file-list="false"-->
          <!--:before-upload="beforeUploadOrg">-->
          <i class="el-icon-document-add"></i>
          <i class="text" @click="batchImport()">批量导入</i>
        <!--</el-upload>-->
      </el-col>
      <el-col class="organization-search">
        <el-form :inline="true" :model="formOrganization" class="demo-form-inline" >
          <el-form-item label>
            <el-cascader size="small" ref="cascaderRegion" :options="optionsRegion" :props="props"
              v-model="formOrganization.administrativeIdList" @change="handleChangeRegion" filterable change-on-select
              placeholder="请选择地区"></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-select size="small" v-model="formOrganization.level" placeholder="全部医院级别">
              <el-option v-for="(item, index) in organizationRank" :key="index" :label="item.label" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label>
            <el-input style="width:140px;" size="small" v-model="formOrganization.name" placeholder="请输入机构名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="small" type="primary" @click="searchOrganization()">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button size="small"  @click="resetOrgOrPerson()">取消搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-table class="rim" ref="multipleOrganization" :data="tableOrganization" tooltip-effect="dark" style="width: 100%">
      <el-table-column prop="orgName" label="医院名称" min-width="100" align="center"></el-table-column>
      <el-table-column prop="orgLevelName" label="医院级别" align="center"></el-table-column>
      <el-table-column prop="provinceName" label="所属省份" align="center"></el-table-column>
      <el-table-column prop="cityName" label="所属城市" align="center"></el-table-column>
      <el-table-column prop="countyName" label="所属区县" align="center"></el-table-column>
      <el-table-column prop="townName" label="所属街道" align="center"></el-table-column>
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        width="140">
        <template slot-scope="scope">
          <el-button @click="detel(scope.row)" type="text" size="small" style="color:red">删除</el-button>
        </template>
      </el-table-column>
      <div slot="empty">
        <div class="table-empty">
          <img src="../../../assets/image/no-content1.png">
          <p>没有机构信息</p>
        </div>
      </div>
    </el-table>
    <div class="pagination">
      <el-pagination background @size-change="handleSizeOrganization" @current-change="handleCurrentOrganization"
        :current-page="formOrganization.pageNum" :page-sizes="[10, 30, 50, 100, 200]" :page-size="formOrganization.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="totalOrganization"></el-pagination>
    </div>
    <el-dialog
      title="添加机构"
      :visible.sync="dialogOrg"
      width="80%"
      top="5vh"
      :before-close="handleClose">
        <check-org
          v-if="dialogOrg"
          :circleId='circleId'
          :roleType='roleType'
          @addOrg="addOrg"
          @handleClose="handleClose">
        </check-org>
    </el-dialog>
    <!-- 删除 弹窗 -->
    <el-dialog
      title="确认删除"
      :show-close="false"
      :visible.sync="deleteVisible"
      :close-on-click-modal="false"
      width="600px"
      center
    >
      <p style="text-align: center;">{{detelMessage}}</p>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmDelete">删 除</el-button>
        <el-button @click="hideDeleteFrom">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleErrorClose"
      center>
      <!--<el-table :data="dialogErrorData" align="center">-->
        <!--<el-table-column property="rowNumber" label="行数" align="center"></el-table-column>-->
        <!--<el-table-column property="wrongData" label="错误提示" align="center"></el-table-column>-->
      <!--</el-table>-->

      <div v-if="importSuccessFlag" style="text-align: center;">
        <div>本次成功导入<span style="color: green;">&nbsp;{{importNum}}条&nbsp;</span>数据</div>
        <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleErrorClose" style="margin-top: 20px;">关闭</el-button>
        </span>
      </div>
      <div v-if="!importSuccessFlag" style="text-align: center;">
        <div v-if="importNum == 0">数据不符合格式要求，请修正后再次导入</div>
        <div v-if="importNum != 0">有<span style="color: red;">&nbsp;{{importNum}}条&nbsp;</span>数据不符合格式要求，请修正后再次导入</div>
        <br>
        <div>
        <span>
          <el-button @click="downloadFile" type="text" size="small" style="color: #449284 !important;">下载错误数据></el-button>
          <!--<a @click="downloadFile">下载错误数据</a>-->
        </span>
        </div>
        <div style="margin-top: 20px;">
        <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleErrorClose" style="float: left;margin-left: 130px;">取 消</el-button>
          <el-upload
               class="bg-uploader"
               action="#"
               :show-file-list="false"
               :before-upload="beforeUploadOrg">
       <el-button type="primary" size="small" style="margin-left: -100px;">重新导入</el-button>
     </el-upload>
      </span>
        </div>
      </div>


    </el-dialog>


    <el-dialog
      title="批量导入"
      :visible.sync="dialogImportVisible"
      width="650px"
      :close-on-click-modal="false"
      @close="handleImportClose"
      center>

      <div style="float:left;width: 250px;">
      <span>1.下载模板，填写信息</span>
      <br>
        <div>
          <el-button type="primary" size="small" style="float:left; margin-top: 30px;" @click="download1">下载模板1</el-button>
        <span style="float:left; margin-top: 72px;margin-left: -90px;">填写机构明细导入</span>
        </div>
        <div>
        <el-button type="primary" size="small" style="margin-top: 30px;margin-left: 48px;" @click="download2">下载模板2</el-button>
        <span style="float: right;margin-top:10px;">填写机构ID导入</span>
        </div>
      </div>
      <div style="float:left;margin-left: 90px;width: 1px;height: 100px; background: #c8cbd2;"></div>
      <div style="margin-left: 400px;height: 130px;">
      <span>2.上传填写好的文件</span>
      <br>
     <el-upload
        class="bg-uploader"
        action="#"
        :show-file-list="false"
        :before-upload="beforeUploadOrg">
       <el-button type="primary" size="small" style="margin-top: 30px;">上传文件</el-button>
     </el-upload>

      </div>
    </el-dialog>

  </div>
</template>

<script>
import { openLoading, closeLoading } from "@/utils/utils";
import { doUpload, getFilePath } from "@/utils/qiniu-util";
import * as operationData from "@/utils/operation";
import { moRelSearch, morDeleteOrg } from '@/utils/yqrange/memberApi';
import { getOrgProvincesReq } from '@/utils/yqrange/rangeApi';
import { uploadOrg } from '@/utils/yqrange/yqrangeApi';
import checkOrg from './checkOrg'
let vm = null;
export default {
  props: {
    circleId: {
      type: Number | String,
      default: 1
    },
    roleType: {
      type: Number | String,
      default: 1
    },
  },
  data() {
    return {
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          if (node.level == 1) {
            let req = {
              provinceId: node.data.value
            };
            vm.GET("basic-data/position/cities", req).then(res => {
              let newData = vm.setMoreOption(res.data.cityList, "cities");
              resolve(newData);
            });
          } else if (node.level == 2) {
            let req = {
              cityId: node.data.value
            };
            vm.GET("basic-data/position/counties", req).then(res => {
              let newData = vm.setMoreOption(res.data.countyList, "counties");
              resolve(newData);
            });
          } else if (node.level == 3) {
            let req = {
              countyId: node.data.value
            };
            vm.GET("basic-data/position/towns", req).then(res => {
              let newData = vm.setMoreOption(res.data.townList, "towns");
              resolve(newData);
            });
          }
        }
      },
      administrativeValue: "",
      optionsRegion: [],
      organizationRank: [],
      tableOrganization: new Array(),
      currentOrganization: 1,
      totalOrganization: 10,
      pageSizeOrganization: 2,
      selectionList:[],
      formOrganization: {
        name: "",
        administrativeId: "",
        administrativeIdList: [],
        level: "",
        chechAll: true,
        pageNum: 1,
        pageSize: 10
      },
      dialogOrg: false,
      deleteVisible: false,
      detelMessage: '',
      clickItem: null,
      dialogVisible: false,
      dialogErrorData: [],
      showImportFlag: false,
      dialogImportVisible: false,
      importMsg: "",
      importSuccessFlag: false,
      importNum: 0,
      dialogTitle: "",
      errorFileUrl: ""
    }
  },
  components: {
    checkOrg
  },
  created() {
    vm = this;
    this.initRange();
    //Idtype:1,内部 2.外部
    vm.idType = localStorage.getItem("storageIdType");
    if(vm.idType == 1){
      this.showImportFlag = true;
    }
    else {
      let highMainManager = localStorage.getItem('highMainManager');
      let mainManager = localStorage.getItem('mainManager');
      let manager = localStorage.getItem('manager');
      if(highMainManager == 1 || mainManager == 1 || manager == 1){
        this.showImportFlag = true;
      }
      else {
        this.showImportFlag = false;
      }
    }
  },
  mounted() {
  },
  methods: {
    initRange() {
      this.getRegionOption();
      this.listLevels();
      this.formOrganization.pageNum = 1;
      this.formOrganization.name = "";
      this.formOrganization.level = "";
    },
    setMoreOption(data, type) {
      let option = [];
      for (let i = 0; i < data.length; i++) {
        let obj = data[i];
        if (type == "cities") {
          obj.label = data[i].cityName;
          obj.value = data[i].cityId;
        } else if (type == "counties") {
          obj.label = data[i].countyName;
          obj.value = data[i].countyId;
        } else if (type == "towns") {
          obj.label = data[i].townName;
          obj.value = data[i].townId;
          obj.leaf = true;
        }
        option.push(obj);
      }
      return option;
    },
    //获取地区
    getRegionOption() {
      openLoading(vm);
      let idType = localStorage.getItem("storageIdType");
      getOrgProvincesReq(idType,this.circleId,1).then(res => {
        closeLoading(this);
        if (res.code == "000000" && res.data) {
          vm.optionsRegion = operationData.setRegionOption2(res.data.provinceList)
          vm.formOrganization.administrativeIdList.push(vm.optionsRegion[0].value);
          vm.getOrganization();
        } else {
          this.$message(res.message);
        }
      }).catch(err => {
        this.$message.error('请求失败');
      });
    },
    //机构搜索
    getOrganizationChoose() {
      let administrativeIdItem = operationData.setAdministrativeId(
        this.formOrganization.administrativeIdList
      );
      if (administrativeIdItem == "000_0" || administrativeIdItem == "000_0_0"){
        administrativeIdItem=""
      }
      let idType = localStorage.getItem("storageIdType");
      let req = {
        circleId: this.circleId,
        districtIds: administrativeIdItem,
        orgLevel: this.formOrganization.level,
        orgName: this.formOrganization.name,
        pageNo: this.formOrganization.pageNum,
        pageSize: this.formOrganization.pageSize,
        idType: idType,
        roleType: this.roleType
      };
      openLoading(vm);
      moRelSearch(req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          this.tableOrganization = res.data.orgList;
          this.totalOrganization = res.data.total;
          vm.setOrgTotal()
        } else {
          this.$message(res.message);
        }
      }).catch(err => {
        this.$message.error('请求失败');
      });
    },

    //查询机构列表
    getOrganization() {
      let idType = localStorage.getItem("storageIdType");

      let administrativeIdItem = "";
      // 如果是外部用户（2），只能看到所在省份的数据
      // if(idType == 2){
      //   let optionRegionArray = new Array();
      //   optionRegionArray.push(this.optionsRegion[0].provinceId);
      //   administrativeIdItem = operationData.setAdministrativeId(
      //     optionRegionArray
      //   );
      // }

      // let administrativeIdItem = "";
      let req = {
        circleId: this.circleId,
        districtIds: administrativeIdItem,
        orgLevel:"",
        orgName: this.formOrganization.name,
        pageNo: this.formOrganization.pageNum,
        pageSize: this.formOrganization.pageSize,
        idType: idType,
        roleType: this.roleType
      };
      openLoading(vm);
      moRelSearch(req).then(res => {
        closeLoading(this);
        if (res.code == "000000") {
          this.tableOrganization = res.data.orgList;
          this.totalOrganization = res.data.total;
          vm.setOrgTotal()
        } else {
          this.$message(res.message);
        }
      }).catch(err => {
        this.$message.error('请求失败');
      });
    },
    //获取医院等级
    listLevels() {
      let req = {};
      vm.GET("contents/courseDoctor/listLevels?sysCode=10", req).then(res => {
        if (res.code == "000000") {
          this.organizationRank = operationData.getLevelList(res.data.list);
        } else {
          this.organizationRank = [
            {
              id: "0",
              label: "全部医院等级"
            }
          ];
        }
      });
    },
    //选择搜索机构方式
    searchOrganization() {
      this.formOrganization.pageNum = 1;
      let searchForm = this.formOrganization;
      if (
        searchForm.administrativeId == "0" &&
        searchForm.administrativeIdList[
        searchForm.administrativeIdList.length - 1
        ] == "0" &&
        searchForm.level == "" &&
        searchForm.name == ""
      ) {
        console.log("wei")
        this.searchOrganizationType = "";
        this.getOrganization();
      } else {
        console.log("choose")
        this.searchOrganizationType = "choose";
        this.getOrganizationChoose();
      }
    },
    //重置机构、人员查询
    resetOrgOrPerson() {
      vm.formOrganization.name = "";
      // vm.formOrganization.administrativeId = "0";
      // vm.formOrganization.administrativeIdList = ["0"];
      vm.formOrganization.administrativeId = vm.optionsRegion[0].id;
      vm.formOrganization.administrativeIdList = [];
      vm.formOrganization.administrativeIdList.push(vm.optionsRegion[0].value);
      vm.formOrganization.level = "";
      vm.formOrganization.pageNum = 1;
      vm.searchOrganization();
    },
    handleChangeRegion(value) {
      let areaId = "000";
      for (let i = 0; i < value.length; i++) {
        areaId += "_" + value[i];
      }
      vm.administrativeValue = areaId;
      console.log(value, vm.administrativeValue);
    },
    //机构table修改
    handleSizeOrganization(val) {
      console.log(`每页 ${val} 条`);
      this.formOrganization.pageSize = val;
      this.searchOrganization();
    },
    handleCurrentOrganization(val) {
      //console.log(`当前页: ${val}`);
      this.formOrganization.pageNum = val;
      if (this.searchOrganizationType == "choose") {
        this.getOrganizationChoose();
      } else {
        this.getOrganization();
      }
    },
    detel(item) {
      this.detelMessage = `删除后 "${item.orgName}" 将无法访问本圈,确定删除吗？`
      this.deleteVisible = true
      this.clickItem = item
    },
    confirmDelete() {
      let params = {
        circleId: this.circleId,
        orgIds: [this.clickItem.id]
      }
      morDeleteOrg(params).then((res) => {
        if (res.code == "000000") {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.deleteVisible = false
          this.searchOrganization()
          this.$emit('refreshRenYuan')
        }
      }).catch(() => {
         this.deleteVisible = false
        this.$message.error('删除失败，请稍后重试');
      })
    },
    hideDeleteFrom() {
      this.deleteVisible = false
      this.detelMessage = ''
      this.clickItem = null
    },
    setOrgTotal() {
      vm.$emit('setOrgTotal',vm.totalOrganization)
    },
    dialogOrgFn() {
      this.dialogOrg = true
    },
    handleClose() {
      this.dialogOrg = false
    },
    addOrg() {
      this.dialogOrg = false
      this.searchOrganization()
      this.$emit('refreshRenYuan')
    },

    // 批量导入
    beforeUploadOrg(file) {

      // // 机构数已超10000，无法导入机构
      // if(vm.totalOrganization > 10000){
      //   this.$message.warning('机构数已超10000，无法导入机构');
      //   return;
      // }

      let name = file.name;
      let type = name.substring(name.lastIndexOf('.') + 1);
      if (type !== 'xls' && type !== 'xlsx') {
        vm.$message({
          message: '上传文件只能是 xls、xlsx格式!',
          type: 'warning'
        });
        return;
      }
        openLoading(vm);

        let formData = new FormData();
        formData.append("circleId", vm.circleId);
        formData.append("file", file);

        // let files = new window.File();

        uploadOrg(formData).then(res => {
          closeLoading(vm);

          if (res.code == "000000") {
            vm.dialogImportVisible = false;

            // 导入成功
            if(res.data.status){

              vm.dialogVisible = true;
              vm.dialogTitle = "导入成功";
              vm.importSuccessFlag = true;
              vm.importNum = res.data.successNum;
              vm.initRange();
              vm.searchOrganization();
              vm.$emit('refreshRenYuan');
            }
            else {

              vm.dialogVisible = true;
              vm.dialogTitle = "导入失败";
              vm.importSuccessFlag = false;
              vm.importNum = res.data.failNum;
              vm.errorFileUrl = res.data.file;

              // this.$message({
              //   type: 'success',
              //   message: '导入成功!'
              // });

            }
          }
          else {
            this.$message({
              type: 'error',
              message: res.message
            });
          }
          // vm.setDialog(res);
        });
      // };
      // reader.readAsDataURL(file);

    },
    handleErrorClose() {
      this.dialogVisible = false;
    },
    // 批量导入
    batchImport(){
      this.dialogImportVisible = true;
    },

    handleImportClose(){
      this.dialogImportVisible = false;
    },

    // 下载模板1
    download1(){
      const url = "https://files.yunqueyi.com/template/import_hospital_by_detail.xlsx";
      window.location.href = url;
    },
    // 下载模板2
    download2(){
      const url = "https://files.yunqueyi.com/template/import_hospital_by_id.xlsx";
      window.location.href = url;
    },
    // 下载错误数据文件
    downloadFile(){
      window.location.href = vm.errorFileUrl;
    }

  }
}
</script>
<style >
/*.organization .el-dialog {*/
  /*max-height: 90%;*/
  /*overflow: scroll;*/
/*}*/
</style>
<style lang="scss" scoped>
.organization {
  .add-organization {
    margin-left: 36px;
    line-height: 20px;
    width: 120px;
    cursor: pointer;
    padding-top: 10px;
    i {
      font-size: 18px;
      margin-right: 2px;
    }

  }
  .organization-search {
    margin-right: 20px;
    text-align: right;
    flex: 1;
  }
}
</style>
