<template>
  <div>
    <d2-container>
      <!-- <template slot="header">首页/数据查询</template> -->
      <div class="main">
        <div class="zt_right">
          <!-- <template slot="header">首页/数据查询</template> -->
          <div class="nav">当前所在位置:首页>组织机构</div>
          <div class="ztnr">
          <div class="right_main">
            <div class="right_title">
              <i class="fa fa-bar-chart" aria-hidden="true" style="padding-right: 5px"></i>
              组织机构
            </div>
            <div class="right_table">
              <el-form :inline="true" :model="formInline" class="demo-form-inline" id="formLabel">
                <div class="float-left">
                  <el-form-item label="机构名称">
                    <!-- <el-autocomplete popper-class="my-autocomplete" v-model="orgName" :fetch-suggestions="querySearch" placeholder="请输入内容" @select="handleSelect">
                      <i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClick">
                      </i>

                      <template slot-scope="{ item }">
                        <div class="name">{{ item.value }}</div>
                         <span class="addr">{{ item.address }}</span>
                      </template>
                    </el-autocomplete> -->
                    <el-input v-model="orgName" placeholder="请输入关键词"></el-input>
                    <!-- <el-input></el-input> -->
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="el-icon-refresh-left" @click="reset">重置</el-button>
                  </el-form-item>
                </div>
                <div class="float-right">
                  <el-form-item>

                    <el-button type="primary" icon="el-icon-plus" @click="dialogFormVisible = true">新建机构</el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="actionUnfoldFunc(true)">全部展开</el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button @click="actionUnfoldFunc(false)">全部折叠</el-button>
                  </el-form-item>
                </div>
              </el-form>
              <el-table :data="tableData1" ref='dataTreeList' style="width: 100%" :header-cell-style="{ background: '#0064b9', color: '#c9f5fa' }" row-key="id" border default-expand-all :tree-props="{children: 'children',hasChildren: 'hasChildren',}">
                <el-table-column prop="orgName" label="组织机构名称" width="350">
                </el-table-column>
                <el-table-column prop="storeTypeName" label="机构类型" align="center">
                </el-table-column>

                <el-table-column prop="orgState" label="机构状态" align="center">
                  <template slot-scope="scope">
                    <div v-if="scope.row.orgState ==0">
                      <span class="off">停用</span>
                    </div>
                    <div v-if="scope.row.orgState ==1">
                      <span class="on">启用</span>
                    </div>
                  </template>
                </el-table-column>
                </el-table-column>
                <el-table-column prop="buildTime" label="创建时间" align="center">
                </el-table-column>
                <el-table-column label="操作" width='150'>
                  <template slot-scope="scope">
                    <el-button @click="handleCheck(1, scope.$index, scope.row)" type="editbtn" class="fa fa-edit" size="mini">编辑</el-button>
                    <el-button @click="delecheck( scope.$index, scope.row)" type="delebtn" class="fa fa-remove" size="mini">删除</el-button>
                    <!-- <el-button @click="delecheck( scope.$index, scope.row)" type="detailbtn" class="fa fa-info-circle" size="mini">查看</el-button> -->
                  </template>
                </el-table-column>
              </el-table>
              <!-- <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="1" :page-sizes="[10, 20, 30, 40]" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total">
              </el-pagination> -->
            </div>
          </div>
          </div>
        </div>
      </div>
      <!-- 新建机构 -->
      <el-dialog title="新建机构" :visible.sync="dialogFormVisible" id="dialogStyle">
        <el-form :model="addOrgForm" :rules="rules" ref="ruleForm">
          <el-form-item label="机构名称" prop="orgName" :label-width="formLabelWidth">
            <el-input v-model="addOrgForm.orgName" style="width:500px"></el-input>
          </el-form-item>
          <el-form-item label="上级机构" prop="parentId" :label-width="formLabelWidth">
            <!-- <el-input type="textarea" v-model="ruleForm.superior" rows="10" style="width:500px"></el-input> -->
            <el-select v-model="addOrgForm.parentId" filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" :loading="loading">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" style="width:500px">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="机构类型" prop="storeTypeName" :label-width="formLabelWidth">
            <el-select v-model="addOrgForm.storeTypeCode" placeholder="请选择">
              <el-option v-for="item in orgTypes" :key="item.index" :label="item.label" :value="item.value">
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="机构状态" prop="orgState" :label-width="formLabelWidth">
            <el-radio-group v-model="addOrgForm.orgState" size="small">
              <el-radio label="1" border>启用</el-radio>
              <el-radio label="0" border>停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm(1,'ruleForm')">立即创建</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </div>
      </el-dialog>
      <!-- 修改机构 -->
      <el-dialog title="编辑机构" :visible.sync="dialogFormVisible1" id="dialogStyle">
        <el-form :model="editOrgForm" :rules="rules" ref="editForm">
          <el-form-item label="机构名称" prop="orgName" :label-width="formLabelWidth">
            <el-input v-model="editOrgForm.orgName" style="width:500px"></el-input>
          </el-form-item>
          <!--   <el-form-item label="上级机构" prop="parentId" :label-width="formLabelWidth">
            <el-select v-model="editOrgForm.parentId" filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="remoteMethod" :loading="loading">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" style="width:500px">
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="机构类型" prop="storeTypeName" :label-width="formLabelWidth">
            <el-select v-model="editOrgForm.storeTypeCode" placeholder="请选择">
              <el-option v-for="item in orgTypes" :key="item.index" :label="item.label" :value="item.value">
                <span style="float: left">{{ item.label }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="机构状态" prop="orgState" :label-width="formLabelWidth">
            <el-radio-group v-model="editOrgForm.orgState" size="small">
              <el-radio label="1" border>启用</el-radio>
              <el-radio label="0" border>停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm(2,'editForm')">立即修改</el-button>
          <el-button @click="dialogFormVisible1 = false">取 消</el-button>
        </div>
      </el-dialog>
    </d2-container>
  </div>
</template>
<script>
import api from "@api";
export default {
  name: "dataQuery",
  data() {
    return {
      filterText: "",
      restaurants: [], //组织机构搜索
      state: "",
      formInline: {
        scanTime: "",
      },
      orgName: null, //机构名称
      // 表格字段
      dataSearchList: [
        {
          directLibrary: "",
          subTreasury: "",
          cfName: "",
          scanStart: "",
          scanEnd: "",
          cfState: "",
        },
      ],
      orgTypes: [
        {
          value: "300001",
          label: "集团",
        },
        {
          value: "300002",
          label: "分公司",
        },
        {
          value: "300003",
          label: "分公司-仓",
        },
      ],
      tableData: [
        {
          id: 1,
          orgName: "中储粮河南分公司",
          storeTypeName: "直属库",
          storeTypeCode: 1,
          orgState: "1",
          parentId: 0,
          buildTime: "2021-10-20 19:37:08",
          children: [
            {
              id: 2,
              orgName: "商丘直属库",
              storeTypeName: "直属库",
              storeTypeCode: 1,
              orgState: "1",
              parentId: 1,
              buildTime: "2021-10-20 19:38:38",
              children: [
                {
                  id: 3,
                  orgName: "宁陵粮油储备公司",
                  storeTypeName: "直属库",
                  storeTypeCode: 1,
                  orgState: "1",
                  parentId: 2,
                  buildTime: "2021-10-20 19:39:02",
                  children: [
                    {
                      id: 4,
                      orgName: "1号仓",
                      storeTypeName: "直属库",
                      storeTypeCode: 1,
                      orgState: "1",
                      parentId: 3,
                      buildTime: "2021-10-20 19:39:49",
                      children: [],
                    },
                    {
                      id: 5,
                      orgName: "2号仓",
                      storeTypeName: "直属库",
                      storeTypeCode: 1,
                      orgState: "1",
                      parentId: 3,
                      buildTime: "2021-10-20 19:39:49",
                      children: [],
                    },
                    {
                      id: 6,
                      orgName: "3号仓",
                      storeTypeName: "直属库",
                      storeTypeCode: 1,
                      orgState: "1",
                      parentId: 3,
                      buildTime: "2021-10-20 19:39:49",
                      children: [],
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
      tableData1: [],
      dialogTableVisible: false,
      dialogFormVisible: false, //新建机构
      dialogFormVisible1: false, //修改机构
      formLabelWidth: "120px",
      form: {
        name: "",
        region: "",
      },
      // 机构类型：集团0  分公司1
      addOrgForm: {
        orgName: "", //机构名称
        parentId: null, //上级机构
        // superior: '',//上级机构
        storeTypeName: "", //机构类型名称
        storeTypeCode: null,
        orgState: "", //机构状态
        // cities: '' //机构状态
      },
      editOrgForm: {
        orgName: "", //机构名称
        parentId: null, //上级机构
        storeTypeName: "", //机构类型名称
        storeTypeCode: null,
        orgState: "", //机构状态
      },
      rules: {
        orgName: [
          { required: true, message: "请输入机构名称", trigger: "blur" },
        ],
      },
      statesArr: [],
      options: [],
      value: [], // 机构类型
      list: [],
      indexData: {},
      loading: false,
      isExpand:true, //折叠状态默认为展开
      states: [
        "Alabama",
        "Alaska",
        "Arizona",
        "Arkansas",
        "California",
        "Colorado",
        "Connecticut",
        "Delaware",
        "Florida",
        "Georgia",
        "Hawaii",
        "Idaho",
        "Illinois",
        "Indiana"
      ],

      // 分页
      pagination: {
        // 每页显示的条数
        pageSize: 10,
        // 当前页
        curPage: 1,
        // 总数
        total: 20,
      },
    };
  },
  watch: {
    filterTest(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    
  },
  mounted() {
    //  setTimeout(()=>{
    //    document.getElementsByClassName(
    //     "el-table__row--level-0"
    //   )[0].style.display = "none";
    //   document.getElementsByClassName(
    //     "el-table__row--level-1"
    //   )[0].style.display = "none";
    //  },100)
    // 获取列表数据
    this.getPageInfo();
    this.restaurants = this.loadAll();
    // 上级机构
    this.getSelectArr();
    /*  this.list = this.statesArr.map(item => {
       console.log(item, 'item')
       return { value: `value:${item}`, label: `label:${item}` };
     }); */
  },

  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    search() {
      // console.log(this.orgName, "this.Name");
      api
        .getOrganizationByName(this.orgName)
        .then((res) => {
          if (res.code == 200) {
            this.$nextTick(() => {
              this.tableData1 = res.data;
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 每页条数改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    // 当前页改变
    handleCurrentChange(val) {
      // this.pagination.curPage = val;
      console.log(`当前页: ${val}`);
    },
    // 编辑
    handleCheck(type, index, row) {
      // console.log(type, index, row, "row");
      this.indexData = row;
      this.dialogFormVisible1 = true;
      this.editOrgForm.orgName = row.orgName;
      /*  if (this.editOrgForm.parentId == 0) {
         // 无上级机构
         this.editOrgForm.parentId = '无'
       } else {
         // 此处应该是根据parentId查询机构
         // api.getOrganizationById(row.parentId).then(res =>{
         //   console.log(res,'根据id查询仓库')
         // }).catch(err => {
         //   console.log(err)
         // })
       } */
      // this.editOrgForm.parentId = row.parentId
      // this.editOrgForm.storeTypeName = row.storeTypeName
      this.editOrgForm.storeTypeCode = row.storeTypeName; //机构类型回显为类型名称
      this.editOrgForm.orgState = row.orgState;
    },
    // 删除
    delecheck(index, row) {
      let id = row.id;
      this.$confirm("确定删除该项记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        api
          .deleOrganization(id)
          .then((res) => {
            // console.log(res, 'res0012')
            this.$nextTick(() => {
              this.getPageInfo();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            });
          })
          .catch((err) => {
            console.log(err, "err");
          });
      });
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    loadAll() {
      return [
        { value: "三全鲜食（北新泾店）", address: "长宁区新渔路144号" },
        {
          value: "Hot honey 首尔炸鸡（仙霞路）",
          address: "上海市长宁区淞虹路661号",
        },
        {
          value: "新旺角茶餐厅",
          address: "上海市普陀区真北路988号创邑金沙谷6号楼113",
        }
      ];
    },
    handleSelect(item) {
      console.log(item);
    },
    handleIconClick(ev) {
      console.log(ev);
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 上级机构选择
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          // console.log(query, 'query')

          this.loading = false;
          // console.log(this.list, 'list')
          this.options = this.list.filter((item) => {
            // console.log(item, 'option-item')
            return item.label.indexOf(query) > -1;
          });
          // console.log(this.options,'options')
        }, 200);
      } else {
        this.options = [];
      }
    },
    // 全部展开 全部折叠
    actionUnfoldFunc(isAss){
      //this.$refs.ctab.handleExpand(isAss)
      this.handleExpand(isAss)
    },
    handleExpand(isAss) {
      // 此判断是否为展开状态或折叠状态--若展开折叠是同一个按钮则无需传参和加此if
      if (this.isExpand == isAss){
        return
      }
      this.isExpand = !this.isExpand
      // this.tableData为返回的二级数据data
      this.$nextTick(() => {
        this.forArr(this.tableData1, this.isExpand)
      })
    },
    // 遍历
    forArr(arr, isExpand) {
      arr.forEach(i => {
        // toggleRowExpansion见element文档
        this.$refs.dataTreeList.toggleRowExpansion(i, isExpand)
        if (i.children) {
          this.forArr(i.children, isExpand)
        }
      })
    },
    // 机构名称查询重置
    reset() {
      // this.tableData1[0] = JSON.parse(JSON.stringify(this.tableData[0]));
      this.orgName = null
      this.getPageInfo();
      // console.log(this.tableData1, "tableData1");
    },
    // 获取机构列表数据
    getPageInfo() {
      /* let params = {
        orgName :Lthis.orgName
      } */
      let orgName;
      orgName == null ? "" : this.orgName;

      api
        .getOrganizationList()
        .then((res) => {
          if (res.code == 200) {
            // console.log(res, 'res机构列表')
            this.tableData1 = res.data;
          }
          // console.log(res, '获取机构列表数据res')
        })
        .catch((err) => {
          console.log(err, "获取机构列表数据err");
        });
    },
    //新建机构校验弹窗form  根据type 判断是新增还是修改
    submitForm(type, formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (type == 1) {
            if (this.addOrgForm.storeTypeCode == 300001) {
              this.addOrgForm.storeTypeName = "集团";
            } else if (this.addOrgForm.storeTypeCode == 300002) {
              this.addOrgForm.storeTypeName = "分公司";
            } else if (this.addOrgForm.storeTypeCode == 300003) {
              this.addOrgForm.storeTypeName = "分公司-仓";
            }
            // this.addOrgForm.parentId==null?null:(this.addOrgForm.parentId+1)

            if (typeof this.addOrgForm.parentId) {
              console.log(this.addOrgForm.parentId, "this.addOrgForm.parentId");
            }
            let data = this.addOrgForm;
            // data.parentId = this.addOrgForm.id

            console.log(this.addOrgForm, data, "data213");
            // 新增接口
            api
              .addOrganization(data)
              .then((res) => {
                // console.log(res, '新增机构成功')
                this.getPageInfo();
                // 新增成功关闭弹窗
                this.dialogFormVisible = false;
              })
              .catch((err) => {
                console.log(err, "新增机构err");
              });
          } else if (type == 2) {
            console.log("编辑弹窗");
            if (this.editOrgForm.storeTypeCode == 300001) {
              this.editOrgForm.storeTypeName = "集团";
            } else if (this.editOrgForm.storeTypeCode == 300002) {
              this.editOrgForm.storeTypeName = "分公司";
            } else if (this.editOrgForm.storeTypeCode == 300003) {
              this.editOrgForm.storeTypeName = "分公司-仓";
            }
            // 当机构类型没有改变时要把storeTypeCode 换回来
            this.editOrgForm.storeTypeName = this.indexData.storeTypeName;
            this.editOrgForm.storeTypeCode = this.indexData.storeTypeCode;
            let editData = {
              id: this.indexData.id,
              orgName: this.editOrgForm.orgName,
              storeTypeName: this.editOrgForm.storeTypeName,
              storeTypeCode: this.editOrgForm.storeTypeCode,
              orgState: this.editOrgForm.orgState,
              parentId: this.indexData.parentId,
            };
            console.log(editData, "editData");
            api
              .editOrganization(editData)
              .then((res) => {
                console.log(res, "修改成功res");
                if (res.code == 200) {
                  this.getPageInfo();
                  this.dialogFormVisible1 = false;
                }
              })
              .catch((err) => {
                console.log(err, "err");
              });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 获取select组织树数据
    getSelectArr() {
      let data = {
        storeTypeCode: null,
      };
      api
        .getOrganizationArr(data)
        .then((res) => {
          if (res.code == 200) {
            // console.log(res, "获取select数据成功");
            this.statesArr = res.data;
            // 将拿到的数据格式化为options数据
            this.list = this.statesArr.map((item) => {
              return { value: `${item.id}`, label: `${item.orgName}` };
            });
          }
        })
        .catch((err) => {
          console.log(err, "err获取select组织树数据");
        });
    },
  },
};
</script>
<style lang="scss" scoped>
/* .main .el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf {
  border-bottom: none ;
} */
// 组织机构输入框
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}

.main {
  height: 100%;
  display: flex;
 
  .el-form--inline .el-form-item .el-form-item__label {
    color: #fff;
  }
  .zt_right {
    width:100%;
    // margin-left: 20px;
    // width: calc(100% - 250px);
    .nav {
      padding: 10px 0 10px 10px;
      color: #fff;

      font-size: 14px;

      background: #004a93;
    }
    .right_main {
      border: 1px solid #67a7df;
      background: #112f5d;

      margin-top: 10px;
      .right_title {
        color: #fff;
        border-bottom: 1px solid #67a7df;
        padding: 10px;
        font-size: 14px;
      }
      .right_table {
        padding: 20px;
      }
    }
  }
}
.float-left {
  float: left;
}
.float-right {
  float: right;
}

.off::before {
  content: "";
  display: inline-block;
  border-radius: 50%;
  padding: 5px;
  color: red;
  background-color: red;
  border-color: red;
  margin-right: 8px;
}
.on::before {
  content: "";
  display: inline-block;
  border-radius: 50%;
  padding: 5px;
  color: #5cb85c;
  background-color: #5cb85c;
  border-color: #5cb85c;
  margin-right: 8px;
}
/* .circle {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #5cb85c;
  margin-right: 8px;
}
.circle1 {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #be0b0b;
  margin-right: 8px;
} */
</style>
