<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="医院名称" prop="hospitalName">
        <el-input
          v-model="queryParams.hospitalName"
          placeholder="请输入医院名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医院类型" prop="hospitalType">
  <el-select v-model="queryParams.hospitalType" placeholder="医院类型" clearable size="small">
        <el-option
          v-for="dict in hospitalTypeOptions"
          :key="dict.dictValue"
          :label="dict.dictLabel"
          :value="dict.dictValue"
        />
      </el-select>
      </el-form-item>
      <el-form-item label="医院等级" prop="hospitalLevel">
        <el-select v-model="queryParams.hospitalLevel" placeholder="医院等级" clearable size="small">
              <el-option
                v-for="dict in hospitalleveOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
      </el-form-item>

      <el-form-item label="省市区" prop="cityIds">
        <el-input
          v-model="queryParams.cityIds"
          placeholder="请输入省市区"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="详细地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入详细地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <el-form-item label="状态" prop="status">
      <el-select v-model="queryParams.status" placeholder="状态" clearable size="small">
        <el-option
          v-for="dict in statusOptions"
          :key="dict.dictValue"
          :label="dict.dictLabel"
          :value="dict.dictValue"
        />
      </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['his:hospital:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['his:hospital:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['his:hospital:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:hospital:export']"
        >导出</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="hospitalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="医院名称" align="center" prop="hospitalName" width="200px"/>
      <el-table-column label="医院类型" align="center" prop="hospitalType" >
        <template slot-scope="scope">
          <dict-tag :options="hospitalTypeOptions" :value="scope.row.hospitalType"/>
        </template>
      </el-table-column>

      <el-table-column label="医院等级" align="center" prop="hospitalLevel">
        <template slot-scope="scope">
          <dict-tag :options="hospitalleveOptions" :value="scope.row.hospitalLevel"/>
        </template>
      </el-table-column>

      <el-table-column label="医院照片" align="center" >
        <template slot-scope="scope">
                <el-popover
                  placement="right"
                  title=""
                  trigger="hover">
                  <img slot="reference" :src="scope.row.imgUrl" width="60px">
                  <img :src="scope.row.imgUrl" style="max-width: 250px;">
                </el-popover>
              </template>
</el-table-column>

      <el-table-column label="省市区" align="center" prop="cityIds" width="150px">
                <template slot-scope="scope">
                          {{scope.row.province}}{{scope.row.city}}{{scope.row.district}}
                </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="address" width="150px"/>

      <el-table-column  label="状态">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column label="处方印章" align="center" prop="sealUrl">
        <template slot-scope="scope">
                <el-popover  v-if="scope.row.sealUrl!=null &&scope.row.sealUrl!=''"
                  placement="right"
                  title=""
                  trigger="hover">
                  <img slot="reference" :src="scope.row.sealUrl" width="60px">
                  <img :src="scope.row.sealUrl" style="max-width: 250px;">
                </el-popover>
              </template>
      </el-table-column>
       <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="联系电话" align="center" prop="phone"  width="150px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:hospital:edit']"
          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            @click="handledetails(scope.row)"
            v-hasPermi="['his:disease:details']"
          >详情</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:hospital:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改医院对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body :rules="rules">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医院名称" prop="hospitalName">
          <el-input v-model="form.hospitalName" placeholder="请输入医院名称" />
        </el-form-item>
        <el-form-item label="医院类型" prop="hospitalType">
    <el-select v-model="form.hospitalType" placeholder="医院类型" clearable size="small" >
          <el-option
            v-for="dict in hospitalTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="医院等级" prop="hospitalLevel">
          <el-select v-model="form.hospitalLevel" placeholder="医院等级" clearable size="small" >
                <el-option
                  v-for="dict in hospitalleveOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="descs" >
          <el-input v-model="form.descs" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="医院照片" >
          <el-upload
            v-model="form.imgUrl"
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar" width="200px">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="省市区" >
          <el-cascader
          ref="citySelect"
          v-model="form.cityIds"
          :options="citys"
          @change="handleCityChange">
          </el-cascader>
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
            <el-input placeholder="请输入内容" v-model="form.address" class="input-with-select" />
          <!--    <el-button slot="append" icon="el-icon-search" @click="openMap"></el-button> -->

        </el-form-item>

        <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="处方印章" prop="sealUrl">
         <el-upload
           v-model="form.sealUrl"
           class="avatar-uploader"
           :action="uploadUrl2"
           :show-file-list="false"
           :on-success="handleAvatarSuccess2"
           :before-upload="beforeAvatarUpload">
           <img v-if="form.sealUrl" :src="form.sealUrl" class="avatar" width="200px">
           <i v-else class="el-icon-plus avatar-uploader-icon"></i>
         </el-upload>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer
        :with-header="false"
        size="75%"
         :title="show.title" :visible.sync="show.open">
     <hospitalDetails  ref="hospitalDetails" />
       </el-drawer>
<el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
       <!--     <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据 -->
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
<!--
<getPointMap :dialogVisible="dialogVisibleMap"
ref="mapfrom"
 title="地图取点" @cancel="mapCancel" @sure="surePoint"/> -->
  </div>
</template>

<script>
import { importTemplate,listHospital, getHospital, delHospital, addHospital, updateHospital, exportHospital } from "@/api/his/hospital";
import {getCitys} from "@/api/store/city";
import hospitalDetails from '../../components/his/hospitalDetails.vue';
import getPointMap from "../../components/getPoint_Map.vue";
import { getToken } from "@/utils/auth";
export default {
  name: "Hospital",
     components: { hospitalDetails,getPointMap },
  data() {
    return {
      dialogVisibleMap:false,
      show:{
        title:"医院详情",
        open:false,
      },
      upload: {
              // 是否显示弹出层
              open: false,
              // 弹出层标题
              title: "",
              // 是否禁用上传
              isUploading: false,
              // 是否更新已经存在的用户数据
              updateSupport: 0,
              // 设置上传的请求头部
              headers: { Authorization: "Bearer " + getToken() },
              // 上传的地址
              url: process.env.VUE_APP_BASE_API + "/his/hospital/importData"
            },
       citys:[],
      // 状态数据字典
      hospitalleveOptions: [],
      statusOptions: [],
      hospitalTypeOptions: [],
      uploadUrl2:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 医院表格数据
      hospitalList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        hospitalName: null,
        hospitalType: null,
        hospitalLevel: null,
        descs: null,
        imgUrl: null,
        cityIds: null,
        province: null,
        city: null,
        district: null,
        address: null,
        lng: null,
        lat: null,
        status: null,
        sealUrl: null,
        phone: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        hospitalName: [
          { required: true, message: "医院名称不能为空", trigger: "blur" }
        ],
        hospitalType: [
          { required: true, message: "医院类型不能为空", trigger: "blur" }
        ],
        hospitalLevel: [
          { required: true, message: "医院等级不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "医院状态不能为空", trigger: "blur" }
        ],
        cityIds: [
          { required: true, message: "省市区不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getCitys();
    this.getList();
    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_hospital_type").then(response => {
      this.hospitalTypeOptions = response.data;
    });
    this.getDicts("sys_hospital_level").then(response => {
         this.hospitalleveOptions = response.data;
       });
  },
  methods: {
    openMap(row){
      setTimeout(() => {
           this.$refs.mapfrom.mapfrom(this.form);
      }, 1);
      this.dialogVisibleMap=true;
    },

    /** 导入按钮操作 */
        handleImport() {
          this.upload.title = "导入";
          this.upload.open = true;
        },
        /** 下载模板操作 */
        importTemplate() {
          importTemplate().then(response => {
            this.download(response.msg);
          });
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
          this.upload.open = false;
          this.upload.isUploading = false;
          this.$refs.upload.clearFiles();
          this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
          this.getList();
        },
        // 提交上传文件
        submitFileForm() {
          this.$refs.upload.submit();
        },
    surePoint(value){
            //获取到地图返回的经纬度
            console.log(value);
            this.form.lat=value.lat;
             this.form.lng=value.lon;
              this.form.address=value.search;
            this.mapCancel();
          },
          mapCancel(){
            this.dialogVisibleMap = false;
          },

    /** 详情按钮 */
    handledetails(row){
        this.show.open=true;
        setTimeout(() => {
             this.$refs.hospitalDetails.getDetails(row.hospitalId);
        }, 1);


    },
   handleCityChange(value) {
     var nodes=this.$refs.citySelect.getCheckedNodes();
     this.form.cityIds=value.toString();
     this.form.province=nodes[0].pathLabels[0];
     this.form.city=nodes[0].pathLabels[1];
     this.form.district=nodes[0].pathLabels[2];
   },
    getCitys(){
        getCitys().then(res => {
          this.loading = false;
          this.citys=res.data;
        })
    },


  handleAvatarSuccess2(res, file) {
        if(res.code==200){
          this.form.sealUrl=res.url;
          self.$forceUpdate()
        }
        else{
          this.msgError(res.msg);
        }

    },

    handleAvatarSuccess(res, file) {
        if(res.code==200){
          this.form.imgUrl=res.url;
          self.$forceUpdate()
        }
        else{
          this.msgError(res.msg);
        }
    },
    beforeAvatarUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return   isLt1M;
    },

    /** 查询医院列表 */
    getList() {
      this.loading = true;
      listHospital(this.queryParams).then(response => {
        this.hospitalList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
     this.form=null;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        hospitalId: null,
        hospitalName: null,
        hospitalType: null,
        hospitalLevel: null,
        descs: null,
        imgUrl: null,
        cityIds: null,
        province: null,
        city: null,
        district: null,
        address: null,
        lng: null,
        lat: null,
        status: null,
        remark: null,
        sealUrl: null,
        phone: null
      };

      this.resetForm("form");
      this.$forceUpdate();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.hospitalId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加医院";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const hospitalId = row.hospitalId || this.ids
      getHospital(hospitalId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改医院";
        this.form.hospitalType = String(this.form.hospitalType)
        this.form.status = String(this.form.status)
        this.form.hospitalLevel = String(this.form.hospitalLevel)
           this.form.cityIds=((this.form.cityIds).split(",")).map(Number)

      });
    },
    /** 提交按钮 */
    submitForm() {
              this.form.cityIds=(this.form.cityIds).toString()
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.hospitalId != null) {
            updateHospital(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHospital(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const hospitalIds = row.hospitalId || this.ids;
      this.$confirm('是否确认删除医院编号为"' + hospitalIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delHospital(hospitalIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有医院数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportHospital(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style>

  .avatar-uploader .el-upload {
     border: 1px dashed #d9d9d9;
     border-radius: 6px;
     cursor: pointer;
     position: relative;
     overflow: hidden;
   }
   .avatar-uploader .el-upload:hover {
     border-color: #409EFF;
   }

   .avatar-uploader-icon {
     font-size: 28px;
     color: #8c939d;
     width: 150px;
     height: 150px;
     line-height: 150px;
     text-align: center;
   }
</style>
