<template>
  <div class="page">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="站点名称" prop="siteName">
        <el-input
          v-model="queryParams['query.siteName']"
          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"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="siteList"
      row-key="id"
      border
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="siteName"
        label="站点名称"
        width="400"
      ></el-table-column>
      <el-table-column
        prop="number"
        label="站点编号"
        width="200"
      ></el-table-column>
  <el-table-column
        prop="address"
        label="站点地址"
        width="200"
      ></el-table-column>
     
      <el-table-column
        prop="status"
        label="状态"
        :formatter="statusFormat"
        width="100"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="200"
      >
        <template slot-scope="scope">
          <span>{{ formatterDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
       
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            >新增</el-button
          >
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改站点对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级站点" prop="parentId">
              <treeselect
                v-model="form.parentId"
                :options="siteOptions"
                :normalizer="normalizer"
                placeholder="选择上级站点"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点名称" prop="siteName">
              <el-input v-model="form.siteName" placeholder="请输入站点名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number
                v-model="form.orderNum"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="请输入地址"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="mobile">
              <el-input
                v-model="form.mobile"
                placeholder="请输入联系电话"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点编号" prop="number">
              <el-input
                v-model="form.number"
                placeholder="请输入站点编号"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="站点状态">
             <el-radio-group v-model="form.status">
                <el-radio
                  v-for="(label, value) in dict.status"
                  :key="value"
                  :label="value"
                  >{{ label }}</el-radio
                >
              </el-radio-group> 

            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="单位介绍" prop="introduce">
              <el-input
                v-model="form.introduce"
                placeholder="请输入单位介绍"
                type="textarea"
                :rows="2"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="中心介绍" prop="summary">
              <el-input
                v-model="form.summary"
                placeholder="请输入中心介绍"
                type="textarea"
                :rows="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </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 { handleTree, formatterDate } from "@/assets/utils";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Dept",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      siteList: [],
      // 站点树选项
      siteOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        "query.siteName": null,
      },
      // 表单参数
      form: {},
      dict: {},
      toString: ["status"],
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级站点不能为空", trigger: "blur" },
        ],
        siteName: [
          { required: true, message: "站点名称不能为空", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" },
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    
  },
  methods: {
    formatterDate(time) {
      return formatterDate(time);
    },
    /** 查询站点列表 */
    getList() {
      this.loading = true;

      let query = {};
      //判断追加百分号
      Object.assign(query, this.queryParams);

      if (query["query.siteName"] != null) {
        query["query.siteName"] = "%" + query["query.siteName"] + "%";
      }
      this.$post("/site/list", query)
        .then((res) => {
          if (res && res.code && res.code == 1) {
            this.siteList = handleTree(res.data.result, "id");
            this.dict = Object.assign({}, this.dict, res.data.dict);
            this.loading = false;
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    /** 转换站点数据结构 */
    normalizer(node) {
      console.log("normalizer", node);
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.siteName,
        children: node.children,
      };
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      try {
        return this.dict["status"][row.status];
      } catch (error) {
        return row.status;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    resetForm(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields();
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: 0,
        siteName: "",
        orderNum: 0,
        address: "",
        mobile: "",
        introduce: "",
        summary: "",
        ancestors: "",
        status: "1",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row.id != undefined) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = "添加站点";
      this.loading = true;
      this.$post("/site/list", {})
        .then((res) => {
          if (res && res.code && res.code == 1) {
            this.siteOptions = handleTree(res.data.result);
            this.loading = false;
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      this.loading = true;
      this.$post("/site/edit", { id: [row.id] })
        .then((res) => {
          if (res && res.code && res.code == 1) {
            res.data.entity = this.util_toString(
              res.data.entity,
              this.toString
            );

            Object.assign(this.form, res.data.entity);

            this.open = true;
            this.title = "修改站点";
            this.loading = false;
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });

      this.$post("/site/list/exclude", { id: [row.id] })
        .then((res) => {
          if (res && res.code && res.code == 1) {
            this.siteOptions = handleTree(res.data.result);
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.loading = true;
      const el = this.$refs.form;
      el.validate((valid) => {
        if (!valid) return;
        this.$post("/site/save", {
          entity: this.form,
        })
          .then((res) => {
            if (res && res.code && res.code == 1) {
              this.loading = false;
              this.reset();
              this.open = false;
              this.getList();
            }
          })
          .catch((error) => {
            this.loading = false;
            this.$message.error(error.message);
          });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let _this=this
      this.$confirm(
        '是否确认删除名称为"' + row.siteName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(function () {
        _this.$post("/site/delete", { id: [row.id] })
          .then((res) => {
            if (res && res.code && res.code == 1) {
              _this.getList();
              _this.$message.success("删除成功");
            }
          })
          .catch((error) => {
            _this.$message.error(error.message);
          });
      });
    },

    // 工具方法，把数字转化为字符串
    util_toString(data, array) {
      const dataCopy = Object.assign({}, data);

      array.forEach((item) => {
        dataCopy[item] =
          dataCopy[item] === undefined ? "" : dataCopy[item] + "";
      });
      return dataCopy;
    },
  },
};
</script>