<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item prop="dictLabel">
        <el-input
          v-model="queryParams.dictLabel"
          placeholder="请输入单位类型名称"
          clearable
          @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="['system:role:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
          >导出数据</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="roleList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" type="index" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="单位类型"
        align="center"
        prop="dictLabel"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="字典键值"
        align="center"
        prop="dictValue"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="字典排序"
        align="center"
        prop="dictSort"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column label="状态" align="center" prop="status" sortable>
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_normal_disable"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" sortable />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        sortable
      />

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
            >删除</el-button
          >
          <el-dropdown
            size="mini"
            @command="(command) => handleCommand(command, scope.row)"
            v-hasPermi="['system:role:edit']"
          >
          </el-dropdown>
        </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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
        <el-form-item label="字典类型" v-show="false">
          <el-input v-model="desensitizedDictType" :disabled="true" />
        </el-form-item>
        <el-form-item label="单位类型" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入单位类型" />
        </el-form-item>
        <el-form-item label="字典键值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入字典键值" />
        </el-form-item>
        <el-form-item label="样式属性" prop="cssClass">
          <el-input v-model="form.cssClass" placeholder="请输入样式属性" />
        </el-form-item>
        <el-form-item label="字典排序" prop="dictSort">
          <el-input-number
            v-model="form.dictSort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="回显样式" prop="listClass">
          <el-select v-model="form.listClass">
            <el-option
              v-for="item in listClassOptions"
              :key="item.value"
              :label="item.label + '(' + item.value + ')'"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea" maxlength="100"
            placeholder="请输入内容"
          ></el-input>
        </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-dialog
      :title="title"
      :visible.sync="openDataScope"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="form.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.dataScope">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="form.dataScope == 2">
          <el-checkbox
            v-model="deptExpand"
            @change="handleCheckedTreeExpand($event, 'dept')"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="deptNodeAll"
            @change="handleCheckedTreeNodeAll($event, 'dept')"
            >全选/全不选</el-checkbox
          >
          <el-checkbox
            v-model="form.deptCheckStrictly"
            @change="handleCheckedTreeConnect($event, 'dept')"
            >父子联动</el-checkbox
          >
          <el-tree
            class="tree-border"
            :data="deptOptions"
            show-checkbox
            default-expand-all
            ref="dept"
            node-key="id"
            :check-strictly="!form.deptCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
        <el-button @click="cancelDataScope">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { unitTypeList, statusUnitType } from "@/api/basic/basic";
import {
  listData,
  getData,
  delData,
  addData,
  updateData,
} from "@/api/system/dict/data";
export default {
  name: "UnitType",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      deptExpand: undefined,
      deptNodeAll: undefined,
      deptOptions: [],
      defaultProps: undefined,
      isLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: "",
      typeId: "",
      // 是否显示弹出层
      openDataScope: false,
      dataScopeOptions: [],
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictType: "bm_unit_type",
        dictLabel: undefined,
      },
      // 表单参数
      form: {
        pId: "1",
        typeName: undefined,
        typeId: undefined,
      },
      // 表单校验
      rules: {
        dictLabel: [
          { required: true, message: "数据标签不能为空", trigger: "blur" },
        ],
        dictValue: [
          { required: true, message: "数据键值不能为空", trigger: "blur" },
        ],
        dictSort: [
          { required: true, message: "数据顺序不能为空", trigger: "blur" },
        ],
      },
      roleList: [],
      // 数据标签回显样式
      listClassOptions: [
        {
          value: "default",
          label: "默认",
        },
        {
          value: "primary",
          label: "主要",
        },
        {
          value: "success",
          label: "成功",
        },
        {
          value: "info",
          label: "信息",
        },
        {
          value: "warning",
          label: "警告",
        },
        {
          value: "danger",
          label: "危险",
        },
      ],
    };
  },
  created() {
    this.getList();
  },
  computed: {
    desensitizedDictType() {
      const dictType = this.form.dictType;
      if (!dictType) {
        return "";
      }
      const len = dictType.length;
      const start = Math.floor(len / 2) - 4;
      const end = Math.floor(len / 2) + 4;
      return dictType.substring(0, start) + "****" + dictType.substring(end);
    },
  },
  methods: {
    dictCrypto(value) {
            return value.replace(reg, "$1****$2")
      },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      unitTypeList(this.queryParams).then((response) => {
        this.roleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    submitDataScope() {},
    cancelDataScope() {},
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        // pId: '1',
        status: "0",
        // name: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加单位类型";
      this.form.dictType = "bm_unit_type";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dictCode = row.dictCode || this.ids;
      getData(dictCode).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改单位类型";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.dictCode != undefined) {
            updateData(this.form).then((response) => {
              this.$store.dispatch(
                "dict/removeDict",
                this.queryParams.dictType
              );
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.$store.dispatch(
                "dict/removeDict",
                this.queryParams.dictType
              );
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    changeStatus(row) {
      let param = {
        id: row.id,
        status: row.status,
      };
      statusUnitType(param).then((response) => {
        this.getList();
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const dictCodes = row.dictCode || this.ids;
      this.$modal
        .confirm('是否确认删除所选择的数据项')
        .then(function () {
          return delData(dictCodes);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$store.dispatch("dict/removeDict", this.queryParams.dictType);
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const formatTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}${month}${day}_${hours}${minutes}${seconds}`;
      };

      const currentTime = formatTime(new Date());
      this.download(
        "/material/bm_unit_type/export",
        {
          ...this.queryParams,
          dataCondition: this.ids,
        },
        `单位类型_${currentTime}.xlsx`
      );
    },
  },
};
</script>
