<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--机构数据-->
      <el-col :span="4" :xs="24">
        <org-tree
          v-model="queryParams.orgId"
          @defaultKey="defaultKeys"
          @checkChange="checkChange"
          @click="handleNodeClick"
        ></org-tree>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <div class="main-right-box">
          <!--    搜索条件    -->
          <div class="main-search-box">
            <el-form
              :model="queryParams"
              ref="queryForm"
              size="small"
              :inline="true"
              v-show="showSearch"
            >
              <el-form-item label="机构名称" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入机构名称"
                  clearable
                  @keyup.enter.native="handleQuery"
                  maxlength="50"
                  @input="inputRestriction"
                />
              </el-form-item>
              <el-form-item label="机构编码" prop="code">
                <el-input
                  v-model="queryParams.code"
                  placeholder="请输入机构编码"
                  clearable
                  @keyup.enter.native="handleQuery"
                  maxlength="50"
                />
              </el-form-item>
              <el-form-item label="机构类型" prop="type">
                <el-select
                  v-model="queryParams.type"
                  placeholder="请选择机构类型"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.sys_org_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="机构状态" prop="isLock">
                <el-select
                  v-model="queryParams.isLock"
                  placeholder="请选择机构状态"
                  clearable
                >
                  <el-option
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-form>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="mini"
                  @click="handleQuery"
                  >搜索</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-refresh"
                  size="mini"
                  @click="resetQuery"
                  >重置</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['system:dept:add']"
                  >新增机构</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-upload2"
                  size="mini"
                  @click="handleExportTotal"
                  v-hasPermi="['system:dept:exportConstruction']"
                >导出物防建设达标情况汇总</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-upload2"
                  size="mini"
                  @click="handleExportDetails"
                  v-hasPermi="['system:dept:exportConstructionDetails']"
                >导出物防建设达标情况明细</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  icon="el-icon-upload2"
                  size="mini"
                  @click="handleExportSecurityWork"
                  v-hasPermi="['system:dept:exportSecurityWork']"
                >导出安全保卫工作情况统计</el-button
                >
              </el-col>
              <right-toolbar
                :showSearch.sync="showSearch"
                @queryTable="getList"
              ></right-toolbar>
            </el-row>
          </div>
          <el-table
            border
            height="646"
            size="small"
            v-loading="loading"
            :data="deptList"
          >
            <el-table-column label="序号" align="center" width="80">
              <template v-slot:default="scope">
                <span v-text="getPageIndex(scope.$index)"> </span>
              </template>
            </el-table-column>
            <el-table-column
              v-if="false"
              prop="name"
              label="机构名称"
            ></el-table-column>
            <el-table-column
              align="center"
              prop="shortName"
              label="机构简称"
            ></el-table-column>
            <el-table-column align="center" prop="type" label="机构类型">
              <template v-slot="scope">
                <dict-tag
                  :options="dict.type.sys_org_type"
                  :value="scope.row.type"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="code"
              align="center"
              label="机构编码"
            ></el-table-column>

            <el-table-column prop="isLock" align="center" label="机构状态">
              <template v-slot="scope">
                <dict-tag
                  :options="dict.type.sys_normal_disable"
                  :value="scope.row.isLock"
                />
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              prop="sort"
              label="排序"
            ></el-table-column>
            <el-table-column
              v-if="false"
              align="center"
              prop="weatherCityCode"
              label="城市天气区域"
            >
              <template slot-scope="r">
                <span>{{ getCode(r.row.weatherCityCode) }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="address" label="地址"></el-table-column> -->
            <!-- <el-table-column label="负责人" align="center">
             <template v-slot:default="scope">
               <span v-text="scope.row.manager"></span>-
               <span v-text="scope.row.managerPhone"> </span>
             </template>
           </el-table-column> -->
            <el-table-column
              v-if="false"
              align="center"
              prop="manager"
              label="负责人"
            ></el-table-column>
            <el-table-column
              v-if="false"
              align="center"
              prop="managerPhone"
              label="负责人电话"
            ></el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="280"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope">
                <!-- <router-link
                   :to="'/system/dept-extend/extend/' + scope.row.id"
                   class="link-type"
                 > -->
                <el-button
                  v-if="
                    scope.row.type == 4 ||
                    scope.row.type == 10 ||
                    scope.row.type == 5
                  "
                  size="mini"
                  type="text"
                  icon="el-icon-plus"
                  v-hasPermi="['system:dept:extend']"
                  @click="handleReplenish(scope.row.id)"
                  >补充信息</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit-outline"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:dept:edit']"
                  >编辑</el-button
                >
                <el-button
                  v-if="!scope.row.source"
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:dept:remove']"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <pagination
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改机构对话框 -->
    <DialogCom
      :title="title"
      :visible.sync="open"
      width="1000px"
      @close="closeHandler"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item
              v-if="this.pId != -1 && !form.source"
              label="所属机构"
              prop="parentId"
            >
              <treeselect
              noResultsText="暂无符合条件的数据"
              noOptionsText="无数据"
              clearValueText="清除"
                v-model="form.parentId"
                :options="deptOptions2"
                :normalizer="tenantIdnormalizer"
                placeholder="请选择所属机构"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="机构名称" prop="name">
              <el-input
                :maxlength="50"
                @input="editRestriction"
                v-model="form.name"
                placeholder="请输入机构名称"
                :disabled="form.source == 1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构简称" prop="shortName">
              <el-input
                v-model="form.shortName"
                :maxlength="50"
                @input="shorteditRestriction"
                placeholder="请输入机构简称"
                :disabled="form.source == 1"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="机构类型" prop="type">
              <el-select
                prop="type"
                label="机构类型"
                v-model="form.type"
                placeholder="请选择机构类型"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.sys_org_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  v-show="
                    addIndex == 2 ||
                    (addIndex == 3 && dict.value == 5) ||
                    (addIndex == 3 && dict.value == 10) ||
                    (addIndex == 3 && dict.value == 6) ||
                    (addIndex == 3 && dict.value == 7)
                  "
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="manager" v-if="false">
              <el-input
                v-model="form.manager"
                placeholder="请输入负责人"
                maxlength="20"
                :disabled="form.source == 1"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序号" prop="sort">
              <el-input-number
                v-model="form.sort"
                controls-position="right"
                style="width: 100%"
                :min="0"
                :max="999999"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" v-if="false">
            <el-form-item label="负责人电话" prop="managerPhone">
              <el-input
                v-model="form.managerPhone"
                placeholder="请输入负责人电话"
                maxlength="16"
                :disabled="form.source == 1"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12" v-if="false">
            <el-form-item label="邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="isEdit" label="机构缩略词" prop="breviary">
              <el-input
                :maxlength="5"
                style="width: 200px;" 
                v-model="form.breviary"
                placeholder="请输入机构缩略词"
              
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构状态" prop="isLock">
              <el-radio-group v-model="form.isLock">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                  :disabled="form.source == 1"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>

        
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="title == '编辑机构信息'"
          type="primary"
          @click="changeSubmitForm"
          >确 定</el-button
        >
        <el-button
          v-if="title == '新增机构信息'"
          type="primary"
          @click="addSubmitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </DialogCom>
    <DialogEdit ref="dialogEdit" @success="refs"></DialogEdit>
  </div>
</template>

<script>
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
} from "@/api/system/dept";
import { deptTreeSelect } from "@/api/system/public";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import DialogEdit from "@/views/system/dept/dialog.edit.vue";
import { findAreaList } from "@/api/core/weather";
import OrgTree from "@/components/orgTree";
export default {
  name: "Dept",
  dicts: ["sys_normal_disable", "sys_org_type"],
  components: { Treeselect, DialogEdit, OrgTree },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 总条数
      total: 0,
      //新增机构打开标识
      addIndex: 1,
      // 机构树选项
      deptOptions: [],
      deptOptions2: [],
      pId: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 机构名称
      deptName: undefined,
      //是否关联下级
      checked: false,
      defaultProps: {
        children: "children",
        label: "shortName",
      },
      isEdit:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
        parentId: undefined,
        checkSub: true,
        type: null,
        code: null,
        isLock:null,
      },
      // 表单参数
      form: {breviary:null},
      // 表单校验
      rules: {
        breviary:[
        { required: true, message: "机构缩略词不能为空", trigger: "blur" },
        ],
        parentId: [
          { required: true, message: "上级机构不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "机构名称不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: "机构类型不能为空", trigger: "change" },
        ],
        orderNum: [
          { required: true, message: "显示排序不能为空", trigger: "blur" },
        ],
        isLock: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        // 同步过来的机构存在座机号的情况
        // phone: [
        //   {
        //     pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        //     message: "请输入正确的手机号码",
        //     trigger: "blur",
        //   },
        // ],
      },
      //默认选中节点
      defaultKeys: [],
      areaList: [],
    };
  },
  computed: {
    isShow() {
      if (this.pId == null && this.pId != -1) {
        return true;
      }
    },
  },
  created() {
    this.getDeptTree();
    this.getList();
    this.getAreaList();
  },
  methods: {
    inputRestriction() {
      // 限制只允许输入汉字、英文和数字
      this.queryParams.name = this.queryParams.name.replace(
        /[^\u4e00-\u9fa5a-zA-Z0-9]/g,
        ""
      );
    },
    editRestriction() {
      // 限制只允许输入汉字、英文和数字
      this.form.name = this.form.name.replace(/[^\u4e00-\u9fa5a-zA-Z0-9]/g, "");
    },
    shorteditRestriction() {
      // 限制只允许输入汉字、英文和数字
      this.form.shortName = this.form.shortName.replace(
        /[^\u4e00-\u9fa5a-zA-Z0-9]/g,
        ""
      );
    },
    getCode(item) {
      if (item != null && item.length > 0) {
        let area = this.areaList.find((v) => v.key === item);
        if (area) {
          return area.value;
        } else {
          return "";
        }
      } else {
        return "";
      }
    },
    closeHandler() {
      // alert(11111)
    },
    getPageIndex($index) {
      //表格序号
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + $index + 1
      );
    },
    //自定义数据
    tenantIdnormalizer(node, instanceId) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.shortName,
        children: node.children,
      };
    },
    /** 下穿状态改变*/
    changeCheckBox() {
      this.getList();
    },
    /** 查询机构下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
        this.defaultKeys.push(response.data[0].id);
        this.queryParams.parentId = response.data[0].id;
        this.handleQuery();
      });
    },
    getAreaList() {
      findAreaList({}).then((response) => {
        this.areaList = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.parentId = data.id;
      this.handleQuery();
    },
    //单选框状态改变
    checkChange(state) {
      this.queryParams.checkSub = state;
      this.handleQuery();
    },
    /** 查询机构列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then((response) => {
        this.deptList = response.data.rows;
        this.total = response.data.total;
this.isEdit=response.isEdit;
        this.loading = false;
       
      });
    },

    handleExportTotal() {
      this.download(
        "system/dept/exportConstruction",
        {
          ...this.queryParams,
        },
        `机构信息管理-物防建设达标情况汇总表_${new Date().getTime()}.xlsx`
      );
    },
    handleExportDetails() {
      this.download(
        "system/dept/exportConstructionDetails",
        {
          ...this.queryParams,
        },
        `机构信息管理-物防建设达标情况明细表_${new Date().getTime()}.xlsx`
      );
    },
    handleExportSecurityWork() {
      this.download(
        "system/dept/exportSecurityWork",
        {
          ...this.queryParams,
        },
        `机构信息管理-安全保卫工作情况统计表_${new Date().getTime()}.xlsx`
      );
    },
    /** 转换机构数据结构 */
    // normalizer(node) {
    //   if (node.children && !node.children.length) {
    //     delete node.children;
    //   }
    //   return {
    //     id: node.id,
    //     label: node.name,
    //     children: node.children,
    //   };
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      // this.getList();
      // this.getDeptTree();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: undefined,
        deptName: undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
        isLock: "0",
        type: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
      this.queryParams.pageNum = 1;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // this.
      this.getList();
    },
    /** 新增按钮操作 */
    async handleAdd() {
      // console.log(this.queryParams.parentId, "this.queryParams.parentId");
      // console.log(this.form.parentId, "this.form.parentId");
      this.addIndex = 3;
      this.reset();
      if (this.queryParams.parentId != undefined) {
        if (this.pId != -1) {
          await deptTreeSelect().then((response) => {
            this.deptOptions2 = response.data;
            this.defaultKeys.push(response.data[0].id);
          });
        }
        this.form.parentId = this.queryParams.parentId;
        this.open = true;
        this.title = "新增机构信息";
      }
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    handleReplenish(id) {
      let link = `/system/dept-extend/extend/${id}`;
      this.$router.push(link);
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.addIndex = 2;
      this.reset();
      getDept(row.id).then((response) => {
        this.form = response.data;

        this.pId = response.data.parentId;
      });
      if (this.pId != -1) {
        this.pId = row.parentId;
        this.form.parentId = row.parentId;
        console.log(this.form, "this.form");
        console.log(this.form.parentId, "this.pId");
        await deptTreeSelect({ removeId: row.parentId, id: row.id }).then(
          (response) => {
            this.deptOptions2 = response.data;
            // this.defaultKeys.push(response.data[0].id);
            this.open = true;
            this.title = "编辑机构信息";
          }
        );
      }
    },
    /** 提交按钮 */
    changeSubmitForm() {
      this.addIndex = 2;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(this.queryParams, "queryParams");
          updateDept(this.form).then((response) => {
            this.$modal.msgSuccess("处理成功");
            this.open = false;
            this.getList();

            this.$store.dispatch("getOrgTree").then(re=>{

            });
            this.$store.dispatch("getDepTree").then(re=>{

            });
            this.$store.dispatch("getBusinessTree").then(re=>{

            });
            this.$store.dispatch("getWholeTree").then(re=>{

            });
            // this.getDeptTree();
          });
        }
      });
    },
    addSubmitForm() {
      this.addIndex = 3;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addDept(this.form).then((response) => {
            this.$modal.msgSuccess("处理成功");
            this.open = false;
            this.getList();
            this.getDeptTree();

            this.$store.dispatch("getOrgTree");
            this.$store.dispatch("getDepTree");
            this.$store.dispatch("getBusinessTree");
            this.$store.dispatch("getWholeTree");
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除名称为"' + row.name + '"的数据项？')
        .then(function () {
          return delDept(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.getDeptTree();
          this.$store.dispatch("getOrgTree");
          this.$store.dispatch("getDepTree");
          this.$store.dispatch("getBusinessTree");
          this.$store.dispatch("getWholeTree");
        })
        .catch(() => {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    showDialogEdit(row) {
      this.$refs.dialogEdit.show(row);
    },
    refs() {
      this.getList();
      this.getDeptTree();
    },
  },
  watch: {
    // 根据名称筛选机构树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
};
</script>

<style lang="scss" scoped>
.status_no_class {
  color: red;
}
</style>
