<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <div class="query-box">
        <div class="query-box__left">
          <el-form-item label="" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入医疗机构名称"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item prop="communityId">
            <el-select
              v-model="queryParams.communityId"
              filterable
              placeholder="请选择医共体"
            >
              <el-option
                v-for="item in cimmunity"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="item.state == 1 ? false : true"
              >
              </el-option>
            </el-select>
          </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-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['medical:mechanism:add']"
              >新增</el-button
            >
          </el-form-item>
        </div>
      </div>
    </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="['medical:mechanism:add']"
          >新增</el-button
        >
      </el-col>
    </el-row> -->

    <!-- <el-table
      v-loading="loading"
      :data="mechanismList"
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      border
    > -->
    <el-table
      v-loading="loading"
      :data="mechanismList"
      row-key="id"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="55" align="center" label="序号" />
      <el-table-column label="医共体名称" align="center" prop="communityName" />

      <el-table-column label="医疗机构代码" prop="code" align="center" />
      <!-- <el-table-column label="机构id" align="center" prop="communityId" /> -->
      <el-table-column label="医疗机构名称" align="center" prop="name" />
      <el-table-column label="医疗机构地址" align="center" prop="address" />
      <el-table-column label="上级机构" align="center" prop="parentName" />
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <!-- <dict-tag :options="stateOptions" :value="scope.row.state" /> -->
          {{ scope.row.state == 1 ? "启用" : "禁用" }}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="250"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['medical:mechanism:edit']"
            style="width: 40px"
            >修改</el-button
          >
          <!-- <el-button
            size="mini"
            type="primary"
            v-hasPermi="['medical:mechanism:add']"
            @click="handleChangeState(scope.row, 0)"
            style="width: 40px"
            >启用</el-button
          > -->
          <el-button
            size="mini"
            type="primary"
            v-hasPermi="['medical:mechanism:add']"
            @click="handleChangeState(scope.row, 1)"
            style="width: 40px"
            >{{ scope.row.state != 1 ? "启用" : "禁用" }}</el-button
          >
          <el-button
            size="mini"
            type="primary"
            @click="handleDelete(scope.row)"
            v-hasPermi="['medical:mechanism:remove']"
            style="width: 40px"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改医疗机构对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="医共体" prop="communityId">
          <el-select
            v-model="form.communityId"
            filterable
            placeholder="请选择医共体"
            style="width: 100%"
            @change="communityIdChange"
          >
            <el-option
              v-for="item in cimmunity"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :disabled="item.state == 1 ? false : true"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="医疗机构代码" prop="code">
          <el-input
            v-model="form.code"
            placeholder="请输入代码"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="医疗机构名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入名称"
            @input="handleChangeName"
          />
        </el-form-item>
        <el-form-item
          label="拼音码"
          prop="params.pyq"
          v-if="form.params !== undefined"
        >
          <el-input v-model="form.params.pyq" disabled />
        </el-form-item>
        <el-form-item
          label="五笔码"
          prop="params.wb"
          v-if="form.params !== undefined"
        >
          <el-input v-model="form.params.wb" disabled />
        </el-form-item>
        <el-form-item label="医疗机构类别" prop="type">
          <el-select
            v-model="form.type"
            placeholder="请选择类别"
            style="width: 100%"
            @change="typeChange"
          >
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级医疗机构" prop="parentId">
          <treeselect
            v-model="form.parentId"
            :options="mechanismOptions"
            :normalizer="normalizer"
            placeholder="请选择上级机构"
          />
        </el-form-item>
        <!-- <el-form-item label="省" prop="province">
          <el-select v-model="form.province" placeholder="请选择省">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-select v-model="form.city" placeholder="请选择市">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="区" prop="area">
          <el-select v-model="form.area" placeholder="请选择区">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item> -->
        <!--省市三级联动-->
        <el-form-item label="所属地域">
          <el-cascader
            v-model="location"
            :options="options"
            :props="{ value: 'label' }"
            @change="handleChangeOptions"
            style="width: 100%"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" 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>
  </div>
</template>

<script>
import {
  listMedicalMechanism,
  getMechanism,
  delMechanism,
  addMechanism,
  updateMechanism,
  exportMechanism,
  getInfo,
} from "@/api/medical/mechanism";
import { listCommunity } from "@/api/medical/community";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import options from "@/utils/options";

export default {
  name: "Mechanism",
  components: {
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 医疗机构表格数据
      mechanismList: [],
      // 医疗机构树选项
      mechanismOptions: [{ id: 0, name: "顶级节点", children: [] }],
      mechanisms: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类别字典
      typeOptions: [],
      // 状态字典
      stateOptions: [],
      // 是否删除字典
      delOptions: [],
      // 查询参数
      queryParams: {
        communityId: null,
        name: null,
      },
      // 表单参数
      form: {
        params: {
          pyq: "",
          wb: "",
        },
        communityId: null
      },
      // 表单校验
      rules: {
        communityId: [
          { required: true, message: "请选择医共体", trigger: "blur" },
        ],
        code: [
          { required: true, message: "请输入医疗机构代码", trigger: "blur" },
        ],
        name: [
          { required: true, message: "请输入医疗机构名称", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择医疗机构类别", trigger: "blur" },
        ],
      },
      cimmunity: [], //医共体ID
      communityId: "",
      options,
      location: [],
    };
  },
  created() {
    this.getList();
    this.getCommunityList();
    this.getDicts("mechanism_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then((response) => {
      this.stateOptions = response.data;
    });
    this.getDicts("del_state").then((response) => {
      this.delOptions = response.data;
    });
  },
  methods: {
    typeChange (val) {
      this.mechanismOptions = []
      this.form.parentId = 0
       var arr = []
      if (!this.form.communityId) {
        this.msgError('请选择医共体')
      } else {
        arr = this.mechanisms.filter(v => v.type == val && v.communityId == this.form.communityId)
      }
      const data = { id: 0, name: "顶级节点", children: [] };
      data.children = this.handleTree(arr, "id", "parentId");
      this.mechanismOptions.push(data)
    },
    communityIdChange (val) {
      this.mechanismOptions = []
      this.form.parentId = 0
       var arr = []
      if (!val) {
        this.msgError('请选择医共体')
      } else {
        arr = this.mechanisms.filter(v => v.type == this.form.type && v.communityId == val)
      }
      const data = { id: 0, name: "顶级节点", children: [] };
      data.children = this.handleTree(arr, "id", "parentId");
      this.mechanismOptions.push(data)
    },
    /** 查询医疗机构列表 */
    getList() {
      this.loading = true;
      listMedicalMechanism(this.queryParams).then((response) => {
        // this.mechanismList = this.handleTree(response.data, "id", "parentId");
        this.mechanismList = response.data
        this.loading = false;
      });
    },
    /** 查询医共体列表 */
    getCommunityList() {
      listCommunity().then((response) => {
        this.cimmunity = response.rows;
      });
    },
    /** 转换医疗机构数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    /** 查询医疗机构下拉树结构 */
    getTreeselect() {
      listMedicalMechanism().then((response) => {
        this.mechanisms = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        code: null,
        communityId: null,
        name: null,
        type: null,
        parentId: null,
        province: null,
        city: null,
        area: null,
        address: null,
        state: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        del: null,
        params: {
          pyq: null,
          wb: null,
        },
      };
      this.location = null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      console.log(this.form.communityId)
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加医疗机构";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getMechanism(row.id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改医疗机构";
        this.location = [
          response.data.province,
          response.data.city,
          response.data.area,
        ];
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateMechanism(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMechanism(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm("是否确认删除这条数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delMechanism(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 省市区
    handleChangeOptions(e) {
      this.form.province = e[0];
      this.form.city = e[1];
      this.form.area = e[2];
    },
    //通过医疗名称获取五笔、拼音
    handleChangeName(e) {
      getInfo(e).then((res) => {
        if (res.code === 200) {
          this.$set(this.form.params, "pyq", res.data.pyq);
          this.$set(this.form.params, "wb", res.data.wb);
        }
      });
    },

    //启用/禁用
    handleChangeState(row, num) {
      const id = row.id || this.ids;
      const parmes = {
        id,
        state: row.state == 1 ? (row.state = 2) : (row.state = 1),
      };
      updateMechanism(parmes).then(() => {
        this.getList();
        // num === 0 ? this.msgSuccess("启用成功") : this.msgSuccess("已禁用");
        this.msgSuccess("修改成功");
      });
    },
  },
};
</script>