<!--设定机构-->
<template>
  <div class="set-rganization-wrap">
    <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" type="primary" @click="resetOrgOrPerson('org')">重置</el-button>
      </el-form-item>
      <el-form-item style="float:right;">
        <el-upload
          v-if="idType == 1 && status4Flag != 1"
          class="upload-excel"
          action="#"
          accept=".xlsx"
          multiple
          :limit="1"
          :before-upload="uploadOrganization"
        >
          <el-button size="small">导入机构名单</el-button>
          <el-button class="down-button" slot="tip" size="small" @click="download('organization')">下载导入模板</el-button>
        </el-upload>
        <div v-if="idType == 1 && status4Flag == 1">
          <el-button size="small" @click="dialogUpload = true">导入机构名单</el-button>
          <el-button class="down-button" slot="tip" size="small" @click="download('organization')">下载导入模板</el-button>
        </div>
      </el-form-item>
    </el-form>

    <el-table
      class="rim"
      ref="multipleOrganization"
      :data="tableOrganization"
      tooltip-effect="dark"
      style="width: 100%"
      @select-all="selectAllOrganization"
      @select="selectOrganization"
    >
      <el-table-column
        type="selection"
        width="55"
        :selectable="selectableTableList"
      ></el-table-column>
      <el-table-column prop="name" label="医院名称" min-width="100" align="center"></el-table-column>
      <el-table-column prop="hospitalLevelName" 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>
      <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, 20, 40]"
        :page-size="formOrganization.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalOrganization"
      ></el-pagination>
    </div>

     <el-dialog title="导入失败" :visible.sync="dialogFail" width="30%" class="dialog-fail" center>
          <div class="fail-type" v-if="failType == 1">
            <p>导入数据量已超限额，请修正后再次导入</p>
            <p class="fail-notice">仅支持一次导入5000条数据</p>
          </div>
          <div class="fail-type" v-if="failType == 2">
            <p>
              有
              <span class="fail-num">{{ failNum }}条</span> 数据不符合格式要求，请修正后再次导入
            </p>
            <p class="fail-notice">仅支持xlsx格式的文件</p>
            <p class="fail-link" @click="download('fail')">下载错误数据></p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-upload
              v-if="uploadType == 'org'"
              class="upload-button"
              action="#"
              accept=".xlsx"
              multiple
              :limit="1"
              :before-upload="uploadOrganization"
            >
              <el-button slot="tip" class="down-button-close" size="small" @click="dialogFail = false">取消</el-button>
              <el-button
                stype="position: absolute;top: -14px;"
                type="primary"
                size="small"
                @click="closeFail()"
              >重新导入</el-button>
            </el-upload>
            <el-upload
              v-if="uploadType == 'person'"
              class="upload-button"
              action="#"
              accept=".xlsx"
              multiple
              :limit="1"
              :before-upload="uploadPerson"
            >
              <el-button slot="tip" class="down-button-close" size="small" @click="dialogFail = false">取消</el-button>
              <el-button
                stype="position: absolute;top: -14px;"
                type="primary"
                size="small"
                @click="closeFail()"
              >重新导入</el-button>
            </el-upload>
          </span>
        </el-dialog>
  </div>
</template>

<script>
let vm = null;
import BreadCrumb from "../../../components/breadcrumb.vue";
import { doUpload, getFilePath } from "../../../utils/qiniu-util";
import { mapGetters } from "vuex";
import { openLoading, closeLoading } from "../../../utils/utils";
import * as commonUtil from "../../../utils/utils";
import * as operationData from "../../../utils/operation";
import { getExeclUrl } from "@/utils/index";
import {
  uploadOrgExcel,
  uploadPersonExcel
} from "@/utils/education/educationApi";
import Sortable from "sortablejs";
export default {
  data() {
    return {
       getRowKeys(row) {
        return row.id;
      },
      status4Flag: '',
      checkTableState: {
        multipleOrganization: "",
        multipleDepartment: "",
        multiplePerson: ""
      },
      formOrganization: {
        name: "",
        administrativeId: "0",
        administrativeIdList: ["0"],
        level: "-1",
        chechAll: true,
        pageNum: 1,
        pageSize: 10
      },
      organizationRegion: [],
      organizationRank: [],
      hasOrganizationInit: false,
      tableOrganization: new Array(),
      multipleSelectionOrganization: [],
      currentOrganization: 1,
      totalOrganization: 10,
      pageSizeOrganization: 2,
      lookedOrganization: [],
      changedOrganization: [],
      changedOrganization2: [],
      optionsRegion: [],
      updateNum: 0,
      dialogSuccess: false,
      failType: 2,
      failNum: 0,
      failExcelUrl: "",
      dialogFail: false,
      uploadType: "",
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          console.log("node", 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);
            });
          }
        }
      }
    }
  },
  created() {
    vm = this;
    vm.idType = localStorage.getItem("storageIdType");
    this.getOrganization();
    this.getRegionOption();
    this.listLevels();
  },
  methods: {
    //查询机构列表
    getOrganization() {
       console.log('=========================getOrganization')
      let req = {
        projectId: this.projectId,
        administrativeId: "",
        hospitalLevel: "",
        hospitalLevel: "",
        // scope: '000',: this.getScope("administrative"),
        scope: '000',
        pageNum: this.formOrganization.pageNum,
        pageSize: this.formOrganization.pageSize
      };
      openLoading(vm);
      // vm.POST("portal/scope/v1/organization", req).then(res => {
      vm.POST("portal/new/scope/org/v1/organization", req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          this.tableOrganization = res.data.organizationList;
          this.totalOrganization = res.data.total;

          vm.initOrganizationStatus();
        } else {
          vm.$message(res.message);
        }
      });
    },
     //设定的行政范围内容
    getScope(type) {
       console.log('=========================getScope')
      if (vm.idType == 2) {
        return null;
      }
      let scope = "";
      let noChangeTree = this.getTreeCheck();
      if (type == "administrative") {
        for (let i = 0; i < this.tagsRegion.length; i++) {
          scope += this.tagsRegion[i].key;
          if (i < this.tagsRegion.length - 1) {
            scope += "|";
          }
        }
      } else if (type == "administrativeUpdate") {
        console.log("this.allSelectedKeys", this.allSelectedKeys);
        if (this.allSelectedKeys.length > 0) {
          for (let i = 0; i < this.allSelectedKeys.length; i++) {
            scope +=
              this.allSelectedKeys[i].key + ":" + this.allSelectedKeys[i].type;
            if (i < this.allSelectedKeys.length - 1) {
              scope += "|";
            }
          }
        } else {
          // let noChangeTree = this.getTreeCheck();
          console.log("noChangeTree值", noChangeTree);
          if (noChangeTree.length > 0) {
            for (let i = 0; i < noChangeTree.length; i++) {
              scope += noChangeTree[i].key + ":" + noChangeTree[i].type;
              if (i < noChangeTree.length - 1) {
                scope += "|";
              }
            }
          } else {
            //选全国项目
            if (this.tagsRegion.length > 0 && this.tagsRegion[0].key == "000") {
              scope = "000:1";
              console.log(this.tagsRegion, "scope", scope);
            }
          }
        }
      }
      //console.log(scope);
      if (scope == "") {
        return null;
      }
      return scope;
    },
    // 获取行政范围树
    getTreeCheck() {
       console.log('=========================getTreeCheck')
      //重构归并树
      // let checkedTree = operationData.getSimpleCheckedNodes(
      //   this.$refs.tree.store
      // );
      let halfCheckedTree = this.$refs.tree.getHalfCheckedKeys();
      let allSelectedKeys = operationData.setSelectedKeys(
        checkedTree,
        halfCheckedTree
      );
      vm.allSelectedKeys = allSelectedKeys;
      //重构内容
      return allSelectedKeys;
    },
     //获取地区select
    getRegionOption() {
       console.log('=========================getRegionOption')
      let req = {};
      openLoading(vm);
      vm.GET("basic-data/position/provinces", req).then(res => {
        closeLoading(vm);
        if (res.code == "000000") {
          vm.optionsRegion = operationData.setRegionOption2(
            res.data.provinceList
          );
        }
      });
    },
     // 初始化机构状态
    initOrganizationStatus() {
       console.log('=========================initOrganizationStatus')
      let tableStatus = this.tableOrganization;
      tableStatus.forEach(row => {
        if (row.status == 1) {
          this.$nextTick(function() {
            this.$refs.multipleOrganization.toggleRowSelection(row);
          });
        }
      });
    },
    // 选择列表
    selectableTableList(row, index) {
        console.log('=========================selectableTableList')
      // if (this.status4Flag == 1) {
      if (row.modifyFlag == 1) {
        return false;
      }
      return true;
      // }
      // return true;
    },
     //搜索机构
    searchOrganization() {
      console.log('=========================searchOrganization')
      this.formOrganization.pageNum = 1;
      let searchForm = this.formOrganization;
      if (
        searchForm.administrativeId == "0" &&
        searchForm.administrativeIdList[
          searchForm.administrativeIdList.length - 1
        ] == "0" &&
        searchForm.level == "-1" &&
        searchForm.name == ""
      ) {
        this.searchOrganizationType = "";
        this.getOrganization();
      } else {
        this.searchOrganizationType = "choose";
        this.getOrganizationChoose();
      }
    },
    //重置机构、人员查询
    resetOrgOrPerson(type) {
      console.log('=========================resetOrgOrPerson')
      if (type == "org") {
        vm.formOrganization.name = "";
        vm.formOrganization.administrativeId = "0";
        vm.formOrganization.administrativeIdList = ["0"];
        vm.formOrganization.level = "-1";
        vm.formOrganization.pageNum = 1;
        vm.searchOrganization();
      }
    },
     // 选择地区
    handleChangeRegion(value) {
       console.log('=========================handleChangeRegion')
      let areaId = "000";
      for (let i = 0; i < value.length; i++) {
        areaId += "_" + value[i];
      }
      vm.administrativeValue = areaId;
      console.log(value, vm.administrativeValue);
    },
    //机构table中勾选一排
    selectAllOrganization(selection) {
       console.log('=========================selectAllOrganization')
      let setList = [];
      let selectList = [];
      for (let i = 0; i < vm.tableOrganization.length; i++) {
        if (vm.tableOrganization[i].modifyFlag == 0) {
          setList.push(vm.tableOrganization[i].id);
        }
      }
      for (let j = 0; j < selection.length; j++) {
        selectList.push(selection[j].id);
      }
      let intersect = operationData.getIntersect(setList, selectList);
      let typeStatus = 0;
      if (intersect.length > 0) {
        typeStatus = 1;
      }
      // let  = this.$refs.multipleTable.selection
      console.log(selection, setList, selectList);
      if (setList.length > 0) {
        let req = {
          ids: setList,
          projectId: this.projectId,
          type: typeStatus
        };
        openLoading(vm);
        vm.PUT("portal/new/scope/org/v1/organization/option", req).then(res => {
          closeLoading(vm);
        });
      }
    },
    //分页
    handleSizeOrganization(val) {
      console.log('=========================handleSizeOrganization')
      console.log(`每页 ${val} 条`);
      this.formOrganization.pageSize = val;
      this.searchOrganization();
    },
    //分页相关
    handleCurrentOrganization(val) {
      console.log('=========================handleCurrentOrganization')
      //console.log(`当前页: ${val}`);
      this.formOrganization.pageNum = val;
      if (this.searchOrganizationType == "choose") {
        this.getOrganizationChoose();
      } else {
        this.getOrganization();
      }
    },
     //机构table中勾选一个
    selectOrganization(selection, row) {
      console.log('=========================selectOrganization')
      console.log("select", selection, row);
      let flag = false;
      for (let i = 0; i < selection.length; i++) {
        if (selection[i].id == row.id) {
          flag = true;
        }
      }
      let req = {
        ids: [row.id],
        projectId: this.projectId,
        type: flag === false ? 0 : 1
      };
      openLoading(vm);
      vm.PUT("portal/new/scope/org/v1/organization/option", req).then(res => {
        closeLoading(vm);
      });
    },
     // 导入机构名单
    uploadOrganization(file) {
       console.log('=========================uploadOrganization')
      vm.dialogFail = false;
      vm.uploadType = "org";
      console.log(file);
      let arr = file.type.split("/");
      let ext = "." + arr[1];
      let name = file.name;
      let reader = new FileReader();
      reader.onload = function(e) {
        let fileJson = {
          fileName: file.name,
          file: e.target.result.substr(e.target.result.indexOf("base64,") + 7),
          ext: ext
        };
        let fileArray = [
          {
            type: "",
            base64: fileJson
          }
        ];
        let req = {
          fileArray: fileArray,
          scopeOfAdministrative: vm.getScope("administrative")
        };
        let projectId = vm.projectId;
        console.log("req", req);
        let reqStr = JSON.stringify(req);
        openLoading(vm);
        uploadOrgExcel(reqStr, projectId).then(res => {
          closeLoading(vm);
          vm.setDialog(res);
        });
      };
      reader.readAsDataURL(file);
    },
    // 下载模板或错误文件
    download(type) {
      console.log('=========================download')
      let downloadUrl = "";
      if (type == "organization") {
        downloadUrl = getExeclUrl(
          "%E6%95%99%E5%9F%B9%E9%A1%B9%E7%9B%AE%E8%AE%BE%E7%BD%AE%E6%9C%BA%E6%9E%84%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
        );
      } else if (type == "person") {
        downloadUrl = getExeclUrl(
          "%E6%95%99%E5%9F%B9%E9%A1%B9%E7%9B%AE%E8%AE%BE%E7%BD%AE%E4%BA%BA%E5%91%98%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
        );
      } else if (type == "fail") {
        downloadUrl = vm.failExcelUrl;
      }
      setTimeout(() => {
        window.open(downloadUrl);
      }, 500);
    },
    // 选择更多地区
    setMoreOption(data, type) {
      console.log('=========================setMoreOption')
      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;
          // obj.leaf = true;
        } else if (type == "towns") {
          obj.label = data[i].townName;
          obj.value = data[i].townId;
          obj.leaf = true;
        }
        option.push(obj);
      }
      return option;
    },
     //获取医院等级
    listLevels() {
        console.log('=========================listLevels')
      let req = {};
      vm.GET("contents/courseDoctor/listLevels?sysCode=10", req).then(res => {
        if (res.code == "000000") {
          // console.log(res);
          this.organizationRank = operationData.getLevelList(res.data.list);
        } else {
          this.organizationRank = [
            {
              id: "0",
              label: "全部医院等级"
            }
          ];
        }
      });
    },
    //机构搜索
    getOrganizationChoose() {
       console.log('=========================getOrganizationChoose')
      // console.log('formOrganization',this.formOrganization);
      let administrativeIdItem = operationData.setAdministrativeId(
        this.formOrganization.administrativeIdList
      );
      let req = {
        projectId: this.projectId,
        administrativeId: administrativeIdItem,
        hospitalLevel: this.formOrganization.level,
        hospitalName: this.formOrganization.name,
        pageNum: this.formOrganization.pageNum,
        pageSize: this.formOrganization.pageSize,
        // scope: this.getScope("administrative")
        scope: '000'
      };
      openLoading(vm);
      // vm.POST("portal/scope/v1/organization/choose", req).then(res => {
      vm.POST("portal/new/scope/org/v1/organization/search", req).then(res => {
        closeLoading(vm);
        console.log(res);
        if (res.code == "000000") {
          this.tableOrganization = res.data.organizationList;
          this.totalOrganization = res.data.total;

          vm.initOrganizationStatus();
        } else {
          vm.$message(res.message);
        }
      });
    },
    // 重新导入
    closeFail() {
        console.log('=========================closeFail')
      vm.dialogFail = false;
    },
    // 继续导入
    closeUpload() {
      console.log('=========================closeUpload')
      vm.dialogUpload = false;
    },
    // 设置导入后的弹框
    setDialog(res) {
      console.log('=========================setDialog')
      if (res.code == "000000") {
        if (res.data.success == true) {
          //导入成功
          vm.dialogSuccess = true;
          vm.updateNum = res.data.total;
          if (vm.uploadType == "org") {
            vm.searchOrganization();
          } else {
            vm.searchPeople();
          }
        } else {
          if (res.data.outCount == true) {
            //导入数据超5000
            vm.failType = 1;
            vm.dialogFail = true;
            vm.failNum = res.data.total;
            vm.failExcelUrl = res.data.url;
          } else {
            //导入失败
            // setTimeout(function() {
            vm.failType = 2;
            vm.dialogFail = true;
            vm.failNum = res.data.total;
            vm.failExcelUrl = res.data.url;
            // }, 800);
          }
        }
      } else {
        //接口失败
        vm.$message.error(res.message);
      }
    },
  }
}
</script>

<style lang="scss" scoped>
</style>
