<template>
  <div class="app-container" >
    <div class="tab-box">
      <div class="f-box" v-for="(item,index) in tablist" :key="index" @click="handleClick1(index)" :class="{ 'active' :activeindex==index}">{{item.name}}</div>
    </div>
    <el-row style="padding: 10px">
      <el-col :span="6">
        <el-card  style="margin-right: 5px; border: none;box-shadow: none;" shadow="never">
          <div class="left-box">
            <div class="title-h">组织架构</div>

            <el-input
              placeholder="请输入机构名称查询"
              v-model="filterText"
              @input="inputDeptName()">
            </el-input>
            <div style="width: 100%; height: 20px"></div>

            <el-tree
              :data="Thetree"
              show-checkbox
              :indent=15
              :props="defaultProps"
              @change="handleChange"
              node-key="id"
              @node-click="activecilck"
              highlight-current
              default-expand-all
              :expand-on-click-node="false"
              :render-content="renderContent">
            </el-tree>
          </div>
        </el-card>
      </el-col>

      <el-col :span="18">
        <el-card style="margin-bottom: 20px;border: none;box-shadow: none;height: 81.5vh;overflow: auto" shadow="never">
<!--          <el-tabs v-model="activeName" @tab-click="handleClick">-->
<!--        用户信息    -->
<!--            <el-tab-pane label="用户信息" name="list">-->
              <template v-if="activeindex == 1">
              <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                       label-width="68px">
                <el-form-item label="" prop="accountName111">
                  <el-input
                    v-model="queryParams.accountName"
                    placeholder="用户名"
                    clearable
                    style="width: 180px"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="" prop="accountName111">
                  <el-input
                    v-model="queryParams.realName"
                    placeholder="真实姓名"
                    clearable
                    style="width: 180px"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="" prop="accountStatus111">
                  <el-select
                    v-model="queryParams.deptId"
                    placeholder="所属机构"
                    clearable
                    style="width: 180px"
                  >
                    <el-option
                      v-for="item in deptListSelect"
                      :key="item.deptId"
                      :label="item.deptName"
                      :value="item.deptId"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="" prop="accountStatus">
                  <el-select
                    v-model="queryParams.accountStatus"
                    placeholder="用户状态"
                    clearable
                    style="width: 180px"
                  >
                    <el-option key="1" label="启用" value="1"/>
                    <el-option key="0" label="禁用" value="0"/>
                  </el-select>
                </el-form-item>

  <!--              <el-form-item style="float: right">-->
  <!--                <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>-->
  <!--                <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>-->
  <!--              </el-form-item>-->
  <!--            </el-form>-->
                <el-form-item style="float: right; margin-right: 0px">
                  <el-button type="primary" icon="el-icon-search" size="" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="" @click="resetQuery">重置</el-button>
                  <el-button
                    type="warning"
                    size=""
                    @click="handleAdd"
                    v-hasPermi="['user:add']"
                  >新增用户
                  </el-button>
                </el-form-item>
              </el-form>
              <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" border>
                    <el-table-column type="selection" width="50" align="center" />

                    <el-table-column label="用户名" align="center" key="accountName" prop="accountName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
                    <el-table-column label="真实姓名" align="center" key="realName" prop="realName" />
                    <el-table-column label="用户角色" align="center" key="roleName" prop="roleName" />

                    <el-table-column label="所属机构" align="center" prop="storeName" width="160">
                      <template slot-scope="scope">
                        <span>{{ scope.row.deptName ? scope.row.deptName : '-' }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="状态" align="center" key="accountStatus" v-if="columns[2].visible">
                      <template slot-scope="scope">
                        <el-switch
                          v-model="scope.row.accountStatus"
                          :active-value="1"
                          :inactive-value="0"
                          @change="handleStatusChange(scope.row)"
                        ></el-switch>
                      </template>
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" prop="createDate" v-if="columns[3].visible" width="160">
                      <template slot-scope="scope">
                        <span>{{ scope.row.createTime }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column
                      label="操作"
                      align="center"
                      width="200px"
                      class-name="small-padding fixed-width"
                    >
                    <!-- v-hasPermi="['system:account:edit']" -->
                    <!-- v-hasPermi="['system:account:delete']" -->

                      <template slot-scope="scope">
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-edit"
                          @click="handleUpdate(scope.row)"
                          v-hasPermi="['user:edit']"
                        >修改</el-button>
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-delete"
                          @click="handleDelete(scope.row)"
                          v-hasPermi="['user:delete']"
                        >删除</el-button>
                        <el-button
                          size="mini"
                          type="text"
                          icon="el-icon-refresh"
                          @click="handleResetPwd(scope.row)"
                          v-hasPermi="['user:delete']"
                        >重置密码</el-button>
  <!--                      <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" >-->
  <!--                      <span class="el-dropdown-link" v-hasPermi="['user:password']">-->
  <!--                        <i class="el-icon-d-arrow-right el-icon&#45;&#45;right"></i>更多-->
  <!--                      </span>-->
  <!--                        <el-dropdown-menu slot="dropdown">-->
  <!--                          <el-dropdown-item command="handleResetPwd" icon="el-icon-key" v-hasPermi="['user:password']"-->
  <!--                                            >重置密码</el-dropdown-item>-->
  <!--                        </el-dropdown-menu>-->
  <!--                      </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"
              />
  <!--          tab第一张-->
            </template>
<!--            </el-tab-pane>-->
<!--       机构信息     -->
<!--            <el-tab-pane  label="机构信息" name="info">-->
              <template v-if="activeindex == 0">

              <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
                  <el-form-item label="父级节点" prop="name" v-if="ruleForm.parentId != 0">
                    <el-cascader :disabled="isTopDept" :options="Thetree" disabled style="width: 670px"
                                 v-model="cascader" :props="defaultProps" @change="handleChanges"  :placeholder="parentName"  ></el-cascader>
                  </el-form-item>

<!--                  <el-form-item label="上级部门" prop="parentId">-->
<!--                    <treeselect v-model="cascader" :options="Thetree" :normalizer="normalizer" @change="handleChanges"  placeholder="啊" />-->
<!--                  </el-form-item>-->
                  <el-form-item v-if="deptType == 2" label="油站名称" prop="deptName">
                    <el-input :disabled="isTopDept" v-model="ruleForm.deptName" style="width: 670px"></el-input>
                  </el-form-item>
                  <el-form-item  v-else label="连锁店/油站名称" prop="deptName">
                    <el-input :disabled="isTopDept" v-model="ruleForm.deptName" style="width: 670px"></el-input>
                  </el-form-item>
                  <el-form-item label="负责人名称" prop="leaderName">
                    <el-input :disabled="isTopDept" v-model="ruleForm.leaderName" style="width: 670px" ></el-input>
                  </el-form-item>
                  <el-form-item label="负责人电话" prop="leaderPhone">
                    <el-input :disabled="isTopDept" v-model="ruleForm.leaderPhone" style="width: 670px"></el-input>
                  </el-form-item>
                  <el-form-item label="机构类型" prop="deptType">
                    <span v-if="isTopDept">
                      <el-radio-group :disabled="isTopDept" v-model="ruleForm.deptType">
                        <el-radio
                          v-for="dict in judgementNodeType(dict.type.node_type)"
                          :key="dict.value"
                          :label="dict.value"
                          v-if="dict.value==ruleForm.deptType"
                        >{{dict.label}}</el-radio>
                      </el-radio-group>
                    </span>
                    <span v-else>
                      <span v-if="isAdd">
                        <span v-if="!parentDeptType">
                          <el-radio-group :disabled="isTopDept" v-model="ruleForm.deptType">
                            <el-radio
                              v-for="dict in judgementNodeType(dict.type.node_type)"
                              :key="dict.value"
                              :label="dict.value"
                            >{{dict.label}}</el-radio>
                          </el-radio-group>
                        </span>
                        <span v-else-if="parentDeptType==='1'">
                          <el-radio-group :disabled="isTopDept" v-model="ruleForm.deptType">
                            <el-radio
                              v-for="dict in judgementNodeType(dict.type.node_type)"
                              :key="dict.value"
                              :label="dict.value"
                              v-if="dict.value!='4'"
                            >{{dict.label}}</el-radio>
                          </el-radio-group>
                        </span>
                        <span v-else-if="parentDeptType==='4'">
                          <el-radio-group :disabled="isTopDept" v-model="ruleForm.deptType">
                            <el-radio
                              v-for="dict in judgementNodeType(dict.type.node_type)"
                              :key="dict.value"
                              :label="dict.value"
                            >{{dict.label}}</el-radio>
                          </el-radio-group>
                        </span>
                        <span v-else-if="parentDeptType==='2'">
                          <el-radio-group :disabled="isTopDept" v-model="ruleForm.deptType">
                            <el-radio
                              v-for="dict in judgementNodeType(dict.type.node_type)"
                              :key="dict.value"
                              :label="dict.value"
                              v-if="dict.value=='3'"
                            >{{dict.label}}</el-radio>
                          </el-radio-group>
                        </span>
                        <span v-else-if="parentDeptType==='3'">
                          <el-radio-group :disabled="isTopDept" v-model="ruleForm.deptType">
                            <el-radio
                              v-for="dict in judgementNodeType(dict.type.node_type)"
                              :key="dict.value"
                              :label="dict.value"
                              v-if="dict.value==ruleForm.deptType"
                            >{{dict.label}}</el-radio>
                          </el-radio-group>
                        </span>
                      </span>
                      <span v-else>
                        <el-radio-group :disabled="isTopDept" v-model="ruleForm.deptType">
                            <el-radio
                              v-for="dict in judgementNodeType(dict.type.node_type)"
                              :key="dict.value"
                              :label="dict.value"
                              v-if="dict.value==ruleForm.deptType"
                            >{{dict.label}}</el-radio>
                          </el-radio-group>
                      </span>
                    </span>
                  </el-form-item>
<!--                  <template v-if="ruleForm.deptType !== '3'">-->
                    <template v-if="ruleForm.deptType == '1' || ruleForm.deptType == '2'">
                    <el-row >
                      <el-col :span="20">
                        <el-form-item label="计费方式" prop="turnoverType">
                          <span v-if="isTopDept  ">
                            <el-radio-group  :disabled="isTopDept" v-model="ruleForm.turnoverType" @input="changeTheBillingRule">
                              <el-radio v-if="ruleForm.turnoverType=='1'" label=1>无限制</el-radio>
                              <el-radio v-if="ruleForm.turnoverType=='5'" label=5>年付费</el-radio>
<!--                              <el-radio v-if="ruleForm.turnoverType=='2'" label=2>时间限制</el-radio>-->
                              <el-radio v-if="ruleForm.turnoverType=='3'" label=3>预付费</el-radio>
                              <el-radio v-if="ruleForm.turnoverType=='4'" label=4>后付费</el-radio>
                            </el-radio-group>
                          </span>
                          <span v-else>
                            <el-radio-group  :disabled="isTopDept" v-model="ruleForm.turnoverType" @input="changeTheBillingRule">
                              <el-radio label=5>年付费</el-radio>
                              <el-radio label=3>预付费</el-radio>
                              <el-radio label=4>后付费</el-radio>
                              <el-radio label=1>无限制</el-radio>

                            </el-radio-group>
                          </span>
                        </el-form-item>
                        <div>

                        </div>
                      </el-col>
                    </el-row>
                    <el-row>
                      <template v-if="ruleForm.turnoverType === '3'">
                        <beforeff :deptId="queryParams.deptId"></beforeff>

                      </template>
                      <template v-if="ruleForm.turnoverType === '4'">
                        <afterff :deptId="queryParams.deptId"></afterff>
                      </template>
                      <template v-if="ruleForm.turnoverType === '5'">
                        <yearff :deptId="queryParams.deptId"></yearff>
                      </template>
                      <template v-if="ruleForm.turnoverType === '6'">
                        <el-col :span="10">

                          <el-form-item label="可创建油站数量" label-width="130px">
<!--                            <el-input-number :disabled="isTopDept" v-model="ruleForm.storeNum" @change="handleChangeInputNumber" :min="1"-->
<!--                                             :max="1000" label="可创建油站数量"></el-input-number>-->
                            <el-input type="number" :disabled="isTopDept" v-model="ruleForm.storeNum":min="1" style="width: 670px" @blur="getMax"
                                      :max="maxNumber">
                              <template slot="append">个</template>
                            </el-input>
                          </el-form-item>
                          <el-form-item label="已建油站数量" label-width="130px">
                            <span>{{ruleForm.storeNums || 0}}</span>
                          </el-form-item>
                        </el-col>
                      </template>
                    </el-row>
                  </template>
                  <template v-if="ruleForm.deptType == '3' ">
                    <el-row >
                      <el-col :span="20">
                        <el-form-item label="计费方式" prop="turnoverType">
                          <span v-if="isTopDept">
                            <el-radio-group  :disabled="isTopDept" v-model="ruleForm.turnoverType" @input="changeTheBillingRule">
                              <el-radio v-if="ruleForm.turnoverType=='1'" label=1>无限制</el-radio>
                              <el-radio v-if="ruleForm.turnoverType=='2'" label=2>时间限制</el-radio>
                            </el-radio-group>
                          </span>
                          <span v-else>
                            <el-radio-group  :disabled="isTopDept" v-model="ruleForm.turnoverType" @input="changeTheBillingRule">
                              <el-radio label=1>无限制</el-radio>
                              <el-radio label=2>时间限制</el-radio>
                            </el-radio-group>
                          </span>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <template v-if="ruleForm.turnoverType === '2'">
                        <el-col :span="12">
                          <el-row>
                            <el-form-item  label="时间限制" prop="turnoverType" >
                              <el-date-picker
                                v-model="beginTime"
                                :disabled="isTopDept"
                                style="width: 140px"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="开始日期">
                              </el-date-picker>
                              至
                              <el-date-picker
                                v-model="endTime"
                                :disabled="isTopDept"
                                style="width: 140px"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="结束日期">
                              </el-date-picker>
                            </el-form-item>
                          </el-row>
                        </el-col>
                      </template>
                      <template v-if="ruleForm.turnoverType === '5'">
                        <el-col :span="10">
                          <el-row>
                            <el-form-item label="时间范围">
                              <el-date-picker
                                :disabled="isTopDept"
                                v-model="beginTime"
                                style="width: 140px"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="开始日期">
                              </el-date-picker>
                              至
                              <el-date-picker
                                :disabled="isTopDept"
                                v-model="endTime"
                                style="width: 140px"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="结束日期">
                              </el-date-picker>
                            </el-form-item>
                          </el-row>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item label="价格">
                            <el-input type="number" :disabled="isTopDept" v-model="ruleForm.prepaidAmount">
                              <template slot="append">万元</template>
                            </el-input>
                          </el-form-item>
                        </el-col>
                      </template>
                      <template v-if="ruleForm.turnoverType === '6'">
                        <el-col :span="10">

                          <el-form-item label="可创建油站数量" label-width="130px">
                            <!--                            <el-input-number :disabled="isTopDept" v-model="ruleForm.storeNum" @change="handleChangeInputNumber" :min="1"-->
                            <!--                                             :max="1000" label="可创建油站数量"></el-input-number>-->
                            <el-input type="number" :disabled="isTopDept" v-model="ruleForm.storeNum":min="1" style="width: 200px" @blur="getMax"
                                      :max="maxNumber">
                              <template slot="append">个</template>
                            </el-input>
                          </el-form-item>
                          <el-form-item label="已建油站数量" label-width="130px">
                            <span>{{ruleForm.storeNums || 0}}</span>
                          </el-form-item>
                        </el-col>
                      </template>
                    </el-row>
                  </template>


                  <el-row v-if="ruleForm.deptType !== '3'">
                    <el-col :span="3">
                      <el-form-item label="设置油站数量">
                        <el-switch
                          :disabled="isTopDept"
                          v-model="storeNum"
                          active-color="#13ce66"
                          inactive-color="#ff4949">
                        </el-switch>
                      </el-form-item>

                    </el-col>
<!--                    可创建油站站点数量-->
                    <el-col>
                      <template v-if="storeNum">
                        <el-col :span="10">

                          <el-form-item label="可创建油站数量" label-width="130px">
<!--                            <el-input-number :disabled="isTopDept" v-model="ruleForm.storeNum" @change="handleChangeInputNumber" :min="1"-->
<!--                                             :max="1000" label="可创建油站数量"></el-input-number>-->
                            <el-input type="number" :disabled="isTopDept" v-model="ruleForm.storeNum":min="1" style="width: 200px" @blur="getMax"
                                      :max="maxNumber">
                              <template slot="append">个</template>
                            </el-input>
                          </el-form-item>

                          <el-form-item label="已建油站数量" label-width="130px">
                            <span>{{ruleForm.storeNums || 0}}</span>
                          </el-form-item>
                        </el-col>
                      </template>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12"><div class="grid-content bg-purple"></div></el-col>
                    <el-col :span="12"><div class="grid-content bg-purple-light"></div></el-col>
                  </el-row>

                  <el-form-item label="状态" prop="name">
                    <el-switch :disabled="isTopDept" v-model="value10" @change="getswitch" ></el-switch>
                  </el-form-item>

                  <template v-if="!isTopDept">
                    <el-form-item v-if="pdinfo == 1">
                      <el-button type="primary" @click="submitForms('ruleForm')">新增</el-button>
                      <!--<el-button @click="resetForm('ruleForm')">重置</el-button> -->
                    </el-form-item>
                    <el-form-item v-if="pdinfo == 2">
                      <el-button type="primary" @click="submitFormseide('ruleForm')" v-hasPermi="['agency:update']">保存</el-button>
                      <!--<el-button @click="resetForm('ruleForm')">重置</el-button> -->
                    </el-form-item>
                  </template>

                </el-form>
              </template>
<!--            </el-tab-pane>-->
<!--       角色信息     -->
<!--            <el-tab-pane label="角色信息" name="duty">-->
              <template v-if="activeindex == 2">

              <el-form :model="queryParams1" ref="queryForm" size="small" :inline="true" label-width="100px">
                <el-form-item label="" prop="dutyName11">
                  <el-input
                    v-model="queryParams1.dutyName"
                    placeholder="角色名称"
                    clearable
                    @keyup.enter.native="handleQuery1"
                  />
                </el-form-item>
                <el-form-item label="" prop="status11">
                  <el-select
                    v-model="queryParams1.status"
                    placeholder="角色状态"
                    clearable
                  >
                    <el-option label="启用" value="A"></el-option>
                    <el-option label="禁用" value="D"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="" prop="accountStatus11">
                  <el-select
                    v-model="queryParams1.deptId"
                    placeholder="所属机构"
                    clearable
                    style="width: 240px"
                  >
                    <el-option
                      v-for="item in deptListSelect"
                      :key="item.deptId"
                      :label="item.deptName"
                      :value="item.deptId"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item style="float: right;margin-right: 0px">
                  <el-button type="primary" icon="el-icon-search" @click="handleQuery1">查询</el-button>
                  <el-button icon="el-icon-refresh" @click="reset2">重置</el-button>

                  <el-button
                    type="warning"
                    plain
                    v-hasPermi="['role:add']"
                    @click="handleAdd1"

                  >新增角色
                  </el-button>
                </el-form-item>
              </el-form>

              <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">

                </el-col>
              </el-row>

              <el-table ref="tables"
                        v-loading="loading"
                        border
                        :data="dutyList">
                <el-table-column label="序号" align="center" type="index" width="50"></el-table-column>
                <el-table-column label="角色名称" align="center" prop="dutyName" />
<!--                <el-table-column label="角色类型" align="center" prop="dutyType" >-->
<!--                  <template slot-scope="scope">-->
<!--                    <span v-if="scope.row.dutyType=='1'">超级管理员</span>-->
<!--                    <span v-if="scope.row.dutyType=='2'">普通管理员</span>-->
<!--                    <span v-if="scope.row.dutyType=='3'">油站角色</span>-->
<!--                    <span v-if="scope.row.dutyType=='4'">公司角色</span>-->
<!--                  </template>-->
<!--                </el-table-column>-->
                <el-table-column label="所属机构" align="center" prop="deptName" />
                <el-table-column label="角色状态" align="center" prop="status" >
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.status"
                      active-value="A"
                      inactive-value="N"
                      @change="handleStatusChangeDuty(scope.row)"
                      :disabled="scope.row.dutyId==2"
                    ></el-switch>
                  </template>
                </el-table-column>
                <el-table-column label="角色描述" align="center" prop="description" >
                  <template slot-scope="scope">
                    {{scope.row.description || "--"}}
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-edit"
                      v-hasPermi="['role:edit']"
                      @click="handleUpdate1(scope.row)"
                    >修改</el-button>
<!--                    :disabled="scope.row.dutyId==2"-->

                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      v-hasPermi="['role:delete']"
                      @click="handleDelete1(scope.row)"
                      :disabled="scope.row.dutyId==2"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="total1>0"
                :total="total1"
                :page.sync="queryParams1.page"
                :limit.sync="queryParams1.pageSize"
                @pagination="getDutyList"
              />
              </template>
<!--            </el-tab-pane>-->

<!--          </el-tabs>-->
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 class="common-dialog" -->
    <el-dialog :title="title" :visible.sync="open"  width="600px" append-to-body :close-on-click-modal="false" >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属机构" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择所属机构" style="width: 100%">
                <el-option
                  v-for="item in deptListSelect"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入用户姓名" maxlength="30" autocomplete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="联系方式" prop="mobile">
              <el-input onkeyup="this.value=this.value.replace(/\D/g,'')" v-model="form.mobile" placeholder="请输入用户的联系方式" maxlength="50" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="登录账号" prop="accountName">
              <el-input v-model="form.accountName" placeholder="登录账号（5-12位大小写字母、数字）" onkeyup="value=value.replace(/[^\x00-\xff]/g, '')" maxlength="50" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-row>


        <template v-if="title == '新增用户信息'">

          <el-row>
          <el-col :span="24">
            <el-form-item v-if="form.id == undefined" label="登录密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入登录密码" maxlength="30" show-password autocomplete="off"/>
            </el-form-item>
          </el-col>
        </el-row>
        </template>

        <el-row>
          <el-col :span="24">
            <el-form-item label="用户角色" prop="roleIds">
              <el-select v-model="form.roleIds"  @change="$forceUpdate(),getCodeByRole($event)" placeholder="请选择角色" style="width: 100%;">
                <el-option
                  v-for="item in rolelist"
                  :key="item.dutyId"
                  :label="item.dutyName"
                  :value="item.dutyId"
                ></el-option>
              </el-select>
              <!-- <div v-if="!rolelist || rolelist.length==0" style="color: red;font-size: 12px">请先为当前机构添加角色信息</div> -->

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

        <el-row>
          <el-col :span="24">
            <el-form-item label="角色状态" prop="accountStatus">
              <el-radio-group v-model="form.accountStatus" @change="$forceUpdate()">
                <el-radio :key=1 :label=1 :value=1>启用</el-radio>
                <el-radio :key=0 :label=0 :value=0>禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center;">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="openDuty" width="700px" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form1.roleName" @input="$forceUpdate()" style="width: 300px" placeholder="请输入角色名称" />
        </el-form-item>
<!--        <el-form-item label="角色类型" prop="roleType">-->
<!--          <el-select-->
<!--            v-model="form1.roleType"-->
<!--            placeholder="角色类型"-->
<!--            @change="changeMenu"-->
<!--            style="width: 300px"-->
<!--          >-->
<!--&lt;!&ndash;            <el-option key="1" label="超级管理员" value="1"/>&ndash;&gt;-->
<!--&lt;!&ndash;            <el-option key="2" label="普通管理员" value="2"/>&ndash;&gt;-->
<!--            <el-option key="3" label="油站角色" value="3"/>-->
<!--            <el-option key="4" label="公司角色" value="4"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="状态">
          <el-radio-group v-model="form1.status">
            <el-radio key="A" label="A" value="A">启用</el-radio>
            <el-radio key="N" label="N" value="N">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form1.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form1.menuCheckStrictly"
            :default-checked-keys="form1.checkedKeys"
            empty-text="加载中，请稍候"
            :props="defaultProps1"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form1.description" type="textarea" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect,
  deptadd,
  deptedit,
  deptDelete,
  Userlist,
  jklist, getDutyList, isTopLevelNodesApi, getMaxNumber, selectChildByDeptId
} from "@/api/system/Site/site";
  // import { getStoreStaffList } from "@/api/staff";
  import { getAccountList, getAccount, delAccount, addAccount, updateAccount, resetAccountPwd, changeAccountStatus } from "@/api/system/account";
  import {getToken} from "@/utils/auth";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import BigNumber from 'bignumber.js';
/*import node from "../../../../gasStation-uni/uni_modules/uview-ui/components/u-parse/node/node.vue";*/
import {dutyDelete, dutyEdit, dutyList, dutyLists} from "@/api/duty/duty";
import {addRole, delRole, getRole, updateRole} from "@/api/system/role";
import {getButtonPermi, treeselect as menuTreeselect} from "@/api/system/menu";
import Yearff from "@/views/Site/components/yearff.vue";
import Beforeff from "@/views/Site/components/before.vue";
import Afterff from "@/views/Site/components/afterff.vue";




export default {
    name: "User",
  computed: {
    node() {
      return node
    }
  },
    dicts: ['node_type'],
    data() {
      const equalToPassword = (rule, value, callback) => {
        console.log("151515151:",this.form.password1,value)
        if (this.form.password !== value) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      };
      return {
        maxNumber:1,
        storeNum: false,
        isEditDept:true,
        isTopDept:true,
        parentDeptType:"",
        isAdd:false,


        timeFrame:[],
        value10:true,
        parentName:'请选择',
        cascader:[],
        storeOptions:[],
        merchantOptions:[],
        beginTime:"",
        endTime:"",
        deleteid:0,
        pdinfo: 1 ,
        isAgencyAdd: false,
        isAgencyEdit: false,
        isAgencyDelete: false,
        activeName: 'list',
        ruleForm: {
          parentId:'',
          deptType:'3',
          status:'qy',
          leaderName:'',
          leaderPhone:'',
          // parentName:'请先选择父级节点',
          deptName: '',
          turnoverLimit: 0,
          turnoverType: "1",
          turnoverTime: '',
          turnoverStartTime:null,
          turnoverEndTime:null,
          rates:0,
          storeNum:0,
          prepaidAmount:0,



        },
        filterText:'',
        xtitle:'',
        // 遮罩层
        loading: true,
        staffOptions: [],
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        openDuty:false,
        merchantId:"",
        form1: { id: '', status: 'A', roleType: '4', description: '' },
        // 角色表格数据
        roleList: [],
        menuExpand: false,
        menuNodeAll: false,
        // 菜单列表
        menuOptions: [],
        defaultProps1: {
          children: "childrens",
          label: "label"
        },
        // 总条数
        total: 0,
        // 用户表格数据
        userList: null,
        // 弹出层标题
        xid:'',
        title: "",
        Thetree:[],
        // 节点树选项
        deptOptions: undefined,
        queryParams1:{
          page:1,
          pageSize:10,
          // 当做机构id使用
          storeId:"",
          deptId:''
        },
        total1:0,
        dutyList:[],
        // 是否显示弹出层

        open: false,
        // 节点名称
        deptName: undefined,
        // 默认密码
        initPassword: undefined,
        // 日期范围
        dateRange: [],
        // 岗位选项
        postOptions: [],
        // 角色选项
        roleOptions: [],
        // 表单参数
        form: {
          accountName:'',
          password:'',
          accountStatus:'1',
          roleIds:[],
          deptId:'',
          code:'',
        },
        deptType:'',

        defaultProps: {
          checkStrictly : 'true',
          children: "childrens",
          label: "label",
          value:"id"
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/importData"
        },
        deptListSelect:[],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userName: '',
          phonenumber: '',
          status: '',
          deptId: ''
        },
        isClick: false,
        // 列信息
        columns: [
          {key: 0, label: `用户编号`, visible: true},
          {key: 1, label: `用户名称`, visible: true},
          {key: 2, label: `用户昵称`, visible: true},
          {key: 3, label: `节点`, visible: true},
          {key: 4, label: `手机号码`, visible: true},
          {key: 5, label: `状态`, visible: true},
          {key: 6, label: `创建时间`, visible: true}
        ],
        rolelist:'',
        // 表单校验
        // 表单校验
        rules1: {
          roleName: [
            { required: true, message: "角色名称不能为空", trigger: "blur" }
          ],
          roleType: [
            { required: true, message: "角色类型不能为空", trigger: "blur" }
          ]
        },
        rules: {
          deptId: [
            { required: true, message: '所属机构不能为空', trigger: 'blur' },
          ],
          realName: [
            { required: true, message: '姓名不能为空', trigger: 'blur' },
          ],
          accountName: [
            { required: true, message: '用户名不能为空', trigger: 'blur' },
          ],
          leaderPhone: [
            { required: true, message: '电话不能为空', trigger: 'blur' },
            { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
          ],
          mobile: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
          ],
          deptType: [
            { required: true, message: '机构类型不能为空', trigger: 'blur' },
          ],
          turnoverType: [
            { required: true, message: '计费方式不能为空', trigger: 'blur' },
          ],

          deptName: [
            { required: true, message: '请输入机构名称', trigger: 'blur' },

          ],
          roleIds: [
            { required: true, message: '请选择角色信息', trigger: 'blur' },

          ],
          accountStatus: [
            { required: true, message: '请选择角色状态', trigger: 'blur' },

          ],
          region: [
            { required: true, message: '请选择活动区域', trigger: 'change' }
          ],
          date1: [
            { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
          ],
          date2: [
            { type: 'date', required: true, message: '请选择时间', trigger: 'change' }
          ],
          type: [
            { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
          ],
          resource: [
            { required: true, message: '请选择活动资源', trigger: 'change' }
          ],
          desc: [
            { required: true, message: '请填写活动形式', trigger: 'blur' }
          ],
          userName: [
            {required: true, message: "用户名称不能为空", trigger: "blur"},
            {min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur'}
          ],
          nickName: [
            {required: true, message: "用户昵称不能为空", trigger: "blur"}
          ],
          password: [
            {required: true, message: "用户密码不能为空", trigger: "blur"},
            {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'}
          ],
          password1: [
            {required: true, message: "用户密码不能为空", trigger: "blur"},
            { required: true, validator: equalToPassword, trigger: "blur" },
            {min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur'}
          ],
          email: [
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"]
            }
          ],
          phonenumber: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            }
          ],
          oldValue:'',

        },
        activeindex:0,
        tablist:[
          {
            name:'机构信息',
          },
          {
            name:'用户信息',
          },
          {
            name:'角色信息',
          },
        ],
        // 判断是否是二级门店
        is2Store:false,
      };
    },
    watch: {
      // 根据名称筛选节点树
      deptName(val) {
        this.$refs.tree.filter(val);
      },
      'ruleForm.turnoverType': function(newValue,oldValue) {
        console.log("oldValue",oldValue)
        this.oldValue = oldValue
      },
    },
    filters:{
      /* 翻译角色 */
      getRolelName:function(roles){
        if (typeof roles !== 'undefined' && roles !== null && Array.isArray(roles)) {
          let roleNames = roles.map(function(role) {
            return role.roleName;
          });
          return roleNames.join(",")
        }else{
          return '未分配角色'
        }
      }
    },
    created() {
      this.getList();
      this.selectChildByDeptIdApi();

      console.log("参数",this.$route)
      if (this.$route.query.activeName){
        this.activeName = this.$route.query.activeName
        if (this.activeName == 'list'){
          this.activeindex = 0
        }
        if (this.activeName == 'info'){
          this.activeindex = 1
        }
        if (this.activeName == 'duty'){
          this.activeindex = 2
        }
        this.handleClick()
        this.handleClick1()

      }else {
        this.activeindex = 0
        this.handleClick1()

      }

      if (this.$route.fullPath) {
        this.getPermi(this.$route.fullPath)
      }

    },
    components: {Afterff, Beforeff, Yearff, Treeselect },
    methods: {
      // 获取权限信息
      getPermi(path){
        let _this = this;
        getButtonPermi({path:path}).then(res => {
          res.data.forEach(item => {
            if (item.sourceCode == "agency:add"){
              _this.isAgencyAdd = true;
            }
            if (item.sourceCode == "agency:update"){
              _this.isAgencyEdit = true;
            }
            if (item.sourceCode == "agency:delete"){
              _this.isAgencyDelete = true;
            }
          })
          console.log(_this.isAgencyAdd,_this.isAgencyDelete,12223)
        })
      },
      // 修改角色类型
      async changeMenu() {
        console.log(this.form1.roleType)
        if (this.form1.roleType == '4') {
          this.merchantId = 2
          this.getMenuTreeselect(2);
        }
        if (this.form1.roleType == '3') {
          this.merchantId = 1
          await this.getMenuTreeselect(1);
          await this.handleCheckedTreeNodeAll(true, 'menu')
        }
      },
      // 表单重置
      reset1() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.menuExpand = false,
          this.menuNodeAll = false,
          this.form1 = {
            id: undefined,
            roleName: '',
            roleType: '4',
            status: "A",
            menuIds: [],
            menuCheckStrictly: true,
            description: ''
          };
        this.resetForm("form1");
      },
      // 取消按钮
      cancel1() {
        this.openDuty = false;
        this.reset1();
      },
      submitForm1: function() {
        this.$refs["form1"].validate(valid => {
          if (valid) {
            this.form1.deptType = this.deptType
            if (this.form1.dutyId) {
              this.form1.menuIds = this.getMenuAllCheckedKeys();
              console.log(this.form1.menuIds)
              updateRole(this.form1).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.openDuty = false;
                this.getDutyList();
              });
            } else {
              this.form1.storeId = this.queryParams1.storeId
              this.form1.menuIds = this.getMenuAllCheckedKeys();
              addRole(this.form1).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.openDuty = false;
                this.getDutyList();
              });
            }
          }
        });
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value, type) {
        if (type == 'menu') {
          let treeList = this.menuOptions;
          for (let i = 0; i < treeList.length; i++) {
            this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
          }
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value, type) {
        console.log(this.menuOptions)
        if (type == 'menu') {
          this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
        }
      },
      // 树权限（父子联动）
      handleCheckedTreeConnect(value, type) {
        if (type == 'menu') {
          this.form1.menuCheckStrictly = value ? true: false;
        }
      },
      handleAdd1(){
        // this.reset1();
        // this.form1.storeId = this.Thetree[0].id
        // this.openDuty = true;
        // this.title = "添加角色";
        // console.log(this.form1)
        this.$router.push({path:"/Site/add",query: { merchantId: this.merchantId }})
      },
      // 查询菜单树结构
      getMenuTreeselect(merchantId) {
        console.log("response")

        // merchantId 代表deptType
        return menuTreeselect({merchantId:merchantId}).then(response => {
          this.menuOptions = response.data;
          return response
        });
      },
      handleDelete1(row){
        const roleIds = row.dutyName;
        this.$modal.confirm('是否确认删除角色名为"' + roleIds + '"的信息？').then(function() {
          return dutyDelete(row.dutyId);
        }).then(() => {
          this.getDutyList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      handleUpdate1(data){
        this.reset1();
        const roleId = data.dutyId
        // this.form1.menuCheckStrictly = false
        // getRole(roleId).then(response => {
        //   this.form1.roleName = response.data.roleInfo.name;
        //   this.form1.roleType = response.data.roleInfo.type;
        //   this.form1.status = response.data.roleInfo.status;
        //   this.form1.dutyId = response.data.roleInfo.id;
        //   this.form1.description = response.data.roleInfo.description;
        //   this.openDuty = true;
        //   this.title = "修改角色";
        //   let checkedKeys = response.data.checkedKeys
        //   this.form1.checkedKeys = checkedKeys
        //   this.merchantId = response.data.roleInfo.type
        //   this.getMenuTreeselect(response.data.roleInfo.type)
        // });

        this.$router.push({path:"/Site/add",query: { dutyId: roleId }})
      },
      handleStatusChangeDuty(data){
        console.log(data)
        dutyEdit(data).then(res => {
          this.$message.success("修改成功")
          this.getDutyList();
        })
      },
      // 搜索角色信息
      handleQuery1(){
        this.queryParams1.page = 1;
        this.getDutyList();
      },
      reset2() {
        this.queryParams1={
          page:1,
          pageSize:10,
          // 当做机构id使用
          storeId:"",
          deptId:''
        }
        this.getDutyList();
      },
      getDutyList(){
        this.loading = true;
        dutyList(this.queryParams1).then(res => {
          this.dutyList = res.data.records;
          this.total1 = res.data.total;
          this.loading = false;
        })
      },
      // 更改计费规则
      async changeTheBillingRule(event) {
        // 如果为修改时则进行提示
        if (this.pdinfo == 2) {
          await this.$confirm('此操作将更改计费规则, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (this.ruleForm.turnoverType=='1'||this.ruleForm.turnoverType=='3'||this.ruleForm.turnoverType=='4'){
              this.beginTime = ""
              this.endTime = ""
            }
            // this.rateClearing()
          }).catch(() => {
            console.log("event",event)
            this.ruleForm.turnoverType = this.oldValue
          });
        }


      },
      // 清空数据
      rateClearing () {
        this.timeFrame =[]
        this.beginTime = ""
        this.endTime = ""
        this.ruleForm.turnoverLimit =  0
        this.ruleForm.turnoverTime =  ''
        this.ruleForm.turnoverStartTime = null
        this.ruleForm.turnoverEndTime = null
        this.ruleForm.rates = 0
        this.ruleForm.storeNum = 0
        this.ruleForm.prepaidAmount = 0
      },
      // 费率计算
      rateCalculation () {
        if (this.ruleForm.turnoverType === '3') {
          // 预付金额
          const turnoverLimit = new BigNumber(this.ruleForm.prepaidAmount?this.ruleForm.prepaidAmount:0);
          // 费率
          const feeRate = new BigNumber(this.ruleForm.rates?this.ruleForm.rates:0);
          if (feeRate == 0) return
          const fee = turnoverLimit.dividedBy(feeRate.dividedBy(0.01));
          this.ruleForm.turnoverLimit = fee.toFixed(2)
        }else if (this.ruleForm.turnoverType === '4'){
          // 实际交易量
          const turnoverLimit = new BigNumber(this.ruleForm.turnoverLimit?this.ruleForm.turnoverLimit:0);
          const feeRate = new BigNumber(this.ruleForm.rates?this.ruleForm.rates:0);
          if (feeRate == 0) return
          const fee = turnoverLimit.times(feeRate.dividedBy(0.01));
          this.ruleForm.prepaidAmount = fee.toFixed(2)
        }
      },
      // 页面初始化
      initPage() {
        this.activeName= 'list',
        // this.activeindex= 0,
        this.userList= 'list',
        // this.cleanUp()
        this.getList()
      },

      // 创建节点类型判断
      judgementNodeType(typeList) {
        let evenNumbers = typeList
        // isClick
        if (this.deptType == 3  || (this.deptType == 2 && !this.isClick)) {
          evenNumbers = typeList.filter(number => number.label === "单油站");
          this.ruleForm.deptType = "3"
        }
        return evenNumbers
      },
      // 状态修改
      getswitch(e){
        console.log(e)
        if(e == true){
          this.ruleForm.status = 'qy'
        }else {
          this.ruleForm.status = 'jy'
        }
      },

      async activecilck(data){

        // 判断是点击还是修改该
        this.isClick = true

        console.log('点树',data)

        console.log("ruleForm",this.ruleForm)

        this.isAdd = false
        this.cleanUp()

        let flag = true
        await this.getIsTopLevelNodesApi(data.id).then(res=>{
          flag = res
          console.log('点树2222',res)

        })
        this.$forceUpdate();
        this.isTopDept = flag


        // 点击树之后
        this.queryParams.deptId = data.id
        this.queryParams1.deptId = data.id
        this.deptType = data.deptType
        this.deptId = data.id
        this.parentDeptType = data.deptType
        // this.activeindex = 0
        // 新增节点
        this.appedit(data.id,data.label)
        // 用户请求
        // this.getList();
        this.onlyGetUser()
        this.getDutyList()
        this.merchantId = data.deptType
        this.getMenuTreeselect(data.deptType);
      },

      // 清除信息
      cleanUp(){
        this.ruleForm = {
          parentId:'',
          deptType:'1',
          status:'qy',
          leaderName:'',
          leaderPhone:'',
          // parentName:'请先选择父级节点',
          deptName: '',
          turnoverLimit: '',
          turnoverType: "1",
          turnoverTime: '',
        }
      },

      // 修改树
      handleChange(value) {
        console.log("ruleForm",value);

      },

      handleChangeInputNumber(value) {
        console.log(value);
      },
      handleChanges(value) {
        let arr = value
        this.ruleForm.parentId = arr[arr.length - 1]
      },

      getMax(val){
        getMaxNumber(this.ruleForm).then(res=>{
          console.log("8888888888",this.ruleForm.storeNum)
          console.log("7777777777",res.data)
          if(res.code ==200){
              this.ruleForm.storeNum=res.data
          }
        });
      },
      //新增节点
      submitForms(formName) {


        console.log("timeFrame ",this.timeFrame)
        console.log("this.ruleForm ",this.ruleForm,this.ruleForm.parentId)
        this.$refs[formName].validate((valid) => {
          if (valid) {
              console.log("timeFrame",this.timeFrame)
            if (this.timeFrame){
              // this.ruleForm.turnoverStartTime = this.timeFrame[0]
              // this.ruleForm.turnoverEndTime = this.timeFrame[1]
            }
            this.ruleForm.turnoverStartTime = this.beginTime
            this.ruleForm.turnoverEndTime = this.endTime
            if (!this.storeNum) {
              this.ruleForm.storeNum = null
            }
            deptadd(this.ruleForm).then(res=>{
              if(res.code == 200){
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.initPage()
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },
      //修改
      submitFormseide(ruleForm){
        this.$refs[ruleForm].validate((valid) => {

          if (valid) {
            if (!this.storeNum) {
              this.ruleForm.storeNum = null
            }
            // if (this.timeFrame){
            //   this.ruleForm.turnoverStartTime = this.timeFrame[0]
            //   this.ruleForm.turnoverEndTime = this.timeFrame[1]
            // }
            this.ruleForm.turnoverStartTime = this.beginTime
            this.ruleForm.turnoverEndTime = this.endTime

            deptedit(this.ruleForm).then(res=>{
              // console.log(res)
              if(res.code == 200){
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                this.getList()
                this.cleanUp
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },
      // resetForm(formName) {
      //
      //   // this.$refs[formName].resetFields();
      // },
      handleClick(tab, event) {
        console.log(this.activeName)
        if (this.activeName==="list"){
          this.onlyGetUser()
        }
        if (this.activeName==="duty"){
          this.getDutyList()
        }
      },
      handleClick1(index) {

        console.log("index参数",index);
        if (index || index==0){
          this.activeindex=index;
        }
        console.log("选项",this.activeindex);

        if (this.activeindex== 0){

        }
        if (this.activeindex== 1){
          this.getList()
        }
        if (this.activeindex== 2){
          this.getDutyList()
        }
      },
      //树形页操作
      //新增树
      append(data) {
        console.log('新增树',data)
        // 清除表单
        this.cleanRuleForm()
        this.activeName = 'info'
        this.activeindex = 0

        // console.log("123",dataid)
        if (data.id !== 100) {
          this.isTopDept = false
        }else {
          this.isTopDept = true

        }
        this.pdinfo = 1
        this.timeFrame = []
        this.beginTime = ""
        this.endTime = ""
        this.parentDeptType = data.deptType
        this.addNode(data.id,data.label,data.deptType)
        // console.log(this.pdinfo)
        event.stopPropagation();
        this.isAdd = true
        // 新增树
        if (data.id == 100) {
          this.is2Store = true
        }else {
          this.is2Store = true
        }
      },
      cleanRuleForm() {
        this.ruleForm= {
          parentId:'',
          deptType:'1',
          status:'qy',
          leader_name:'',
          leader_phone:'',
          // parentName:'请先选择父级节点',
          deptName: '',
          turnoverLimit: '',
          turnoverType: "1",
          turnoverTime: '',
        }
      },
      // 新增数据
       addNode(id,label,deptType) {
        let _this = this
        // 默认类型
        this.isClick = false
         this.activeindex = 0
        this.ruleForm.deptType = deptType
        this.$nextTick(() => {
          console.log("新增树的返回222", this.ruleForm,id,label);
        });

        // if (id != 100) {
        //   this.isTopDept = false
        // }

        // _this.ruleForm.deptType = '1'
        // 点击树获取部门信息
         this.cascader = []
         let fanCascader = []

         Userlist(id).then(async res=>{
           console.log(res ,263)
             this.deptType = res.data.deptType
             this.parentName = res.data.parentName
           // if (res.data.parentId==0){
             this.ruleForm.parentId = res.data.deptId
           if (this.ruleForm.parentId == 100) {
             this.is2Store = true
           }else {
             this.is2Store = false

           }
           // }else {
           //   this.ruleForm.parentId = res.data.parentId
           // }

             let pid = res.data.parentId
             fanCascader.push(res.data.deptId)
             while (pid!=0){
              await Userlist(pid).then(re=> {
                  pid = re.data.parentId
                 fanCascader.push(re.data.deptId)
               })
             }
             this.cascader = fanCascader.reverse()
             this.isTopDept = false
           console.log( this.ruleForm.parentId ,111)
           })



      },
      //修改树
      appedit(id,label) {
        this.pdinfo = 2

        console.log("点击树获取部门信息",id)
        // 点击树获取部门信息
        Userlist(id).then(res=>{
          let ancestors = res.data.ancestors.slice(2).toString();
          this.parentName = res.data.parentName
          this.ruleForm = res.data

          // this.ruleForm.parentId = res.data.parentId
          // this.ruleForm.status = res.data.status
          // this.ruleForm.leaderName = res.data.leaderName
          // this.ruleForm.leaderPhone = res.data.leaderPhone
          // this.ruleForm.turnoverType = res.data.turnoverType
          // this.ruleForm.turnoverType = res.data.turnoverType


          if (this.ruleForm.turnoverStartTime) {
            const date = new Date(this.ruleForm.turnoverStartTime);
            // this.timeFrame[0] = date.toString();
            // this.beginTime = date.toString();
            this.timeFrame[0] = date;
            this.beginTime = date;
          }
          if (this.ruleForm.turnoverEndTime) {
            const date = new Date(this.ruleForm.turnoverEndTime);
            // this.timeFrame[1] = date.toString();
            // this.endTime = date.toString();
            this.timeFrame[1] = date;
            this.endTime = date;
          }
          if (this.ruleForm.storeNum) {
            this.storeNum = true
          }
          if(res.data.status === 'qy'){
            this.value10 = true
          }else {
            this.value10 = false
          }

          let temp = ancestors.split(',')
          this.cascader = []
          temp.forEach(it=>{
            this.cascader.push(parseInt(it))
          })
          this.$forceUpdate()
          // console.log(this.cascader)
        })
        this.ruleForm.deptId = id
        // this.ruleForm.parentId = data.id,
        this.ruleForm.deptName = label
      },
      //删除树
      remove(node, data) {
        this.deleteid = data.id
        this.opendelete()

      },
      opendelete() {
        this.$confirm('此操作将永久删除该机构, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deptDelete(this.deleteid).then(res=>{
            // console.log(res)
            if(res.code == 200){
              this.initPage();
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.cleanUp
            }
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // <el-button size="mini" type="text" on-click={ () => this.appedit(data) }>修改</el-button>
      renderContent(h, { node, data, store }) {
        // console.log("node",node)
        // console.log("data",data)
        // console.log("store",store)
        let isAdd =  data.deptType == '3'

        return (

          <div class="custom-tree-node" style="display: flex;align-items: center;">
          <span class="custom-tree-box">{node.label}</span>
          <span style="display: flex;align-items: center;">
            {!isAdd && this.isAgencyAdd ?


              < img alt="" src="https://www.youkerr.com/add" style=" width: 20px;height: 20px;  " on-click={() => this.append(data)}/>
              : null
            }
            {node.level !== 1 && this.isAgencyDelete ?
              < img alt="" src="https://www.youkerr.com/del" style=" width: 20px;height: 20px;  " on-click={() => this.remove(node, data)}/>

              : null
            }
          </span>
        </div>);
      },


      async getIsTopLevelNodesApi(deptId) {
        let flag = false
        await isTopLevelNodesApi({deptId:deptId}).then(res =>{
          if (res.code === 200) {
            flag = res.data
          }
        })
        return flag
      },

      /** 查询用户列表 */
      async getList() {
        console.log("123123123",this.form)
        await deptTreeSelect({deptName :this.filterText}).then(response => {
          this.Thetree = response.data
          if(this.Thetree.length>0 && !this.queryParams.deptId) {
            this.queryParams.deptId = this.Thetree[0].id
            this.deptId = this.Thetree[0].id
            this.appedit(this.deptId)
            console.log("fdfdnfdfdfddf",this.Thetree)
            this.form.deptType = this.Thetree[0].deptType
            this.queryParams1.deptId = this.Thetree[0].id
            console.log("this.Thetree",this.Thetree[0])
          }

        });
        this.loading = true;
        // this.addDateRange(this.queryParams, this.dateRange)
        console.log(this.queryParams,111)
        listUser(this.queryParams).then(response => {
          this.userList = response.data.records;
          this.total = response.data.total;
          this.total = response.data.total;
            this.loading = false;
          }
        );
      },
      selectChildByDeptIdApi() {
        selectChildByDeptId().then(res=>{
          this.deptListSelect = res.data
        })
      },



      onlyGetUser(){
        this.loading = true;
        console.log(this.queryParams,222)
        // this.addDateRange(this.queryParams, this.dateRange)
        listUser(this.queryParams).then(response => {
            this.userList = response.data.records;
            this.total = response.data.total;
            this.total = response.data.total;
            this.loading = false;
          }
        );
      },
      // getStaffList() {
      //   const storeId = this.form.storeId ? this.form.storeId : 0;
      //   getStoreStaffList(storeId).then(response => {
      //     this.staffOptions = response.data.staffList;
      //   });
      // },

      /** 查询节点下拉树结构 */
      getDeptTree() {
        deptTreeSelect().then(response => {
          this.deptOptions = response.data;
        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        // console.log(data)
        this.xid  = data.id
        this.queryParams.deptId = data.id
        this.xtitle = data.label
        this.getList()




      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要"' + text + '""' + row.realName + '"用户吗？').then(function () {
          return updateUser(row);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });

        // scope.row.accountStatus

        // this.$confirm('确认要"' + text + '""' + row.realName + '"用户吗？', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
        //   changeUserStatus(row.userId, row.status).then(res=>{
        //     this.$message({
        //       type: 'success',
        //       message: text+'成功!'
        //     });
        //   })
        // }).catch(() => {

        // });


      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        // console.log('转换部门数据结构',node)
        if (node.childrens && !node.childrens.length) {
          delete node.childrens;
        }
        return {
          id: node.id,
          label: node.label,
          children: node.childrens
        };
      },
      // 表单重置
      reset() {
        this.form = {
          userId: undefined,
          deptId: undefined,
          userName: undefined,
          nickName: undefined,
          password: undefined,
          phonenumber: undefined,
          email: undefined,
          sex: undefined,
          status: "0",
          remark: undefined,
          postIds: [],
          // roleIds: []
          roleIds: ''
        };
        this.resetForm("form");
      },


      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.queryParams.deptId = undefined;
        this.$refs.tree.setCurrentKey(null);
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        // this.ids = selection.map(item => item.userId);
        this.ids = selection.map(item => item.acctId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      // 更多操作触发
      handleCommand(command, row) {
        switch (command) {
          case "handleResetPwd":
            this.handleResetPwd(row);
            break;
          case "handleAuthRole":
            this.handleAuthRole(row);
            break;
          default:
            break;
        }
      },

      // 获取角色信息
      getRoleList(permissionType) {
        let par={
          permissionType:permissionType
        }
        getDutyList(par).then(res=>{
          this.rolelist = res.data
        })
      },
      // 获取角色信息
      getRoleList1(storeId) {
        dutyLists({storeId:storeId}).then(res => {
          this.rolelist = res.data
        })
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.open = true
        this.title = "新增用户信息"
        this.resetForm()
        let permissionType
        if (this.deptType === "3") {
          permissionType = 'staff'
        }else {
          permissionType = 'system'
        }
        // this.getRoleList(permissionType);
        this.getRoleList1(this.queryParams1.storeId);


      },
      resetForm () {
        this.form= {
          accountName:'',
          password:'',
          accountStatus:1
        }
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        console.log('修改用户信息',row)
        this.title = '修改用户信息'
        const app = this;
        app.reset();
        app.open = true;
        app.form = row

        app.form.roleIds = Number(app.form.roleIds);

        app.form.password1 = row.password

        //获取角色
        let permissionType

        if (row.deptType === "3") {
          permissionType = 'staff'
        }else {
          permissionType = 'system'
        }
        // this.getRoleList(permissionType);
        this.getRoleList1(row.deptId);

      },

      // 角色过滤
      /** 重置密码按钮操作 */
      handleResetPwd(row) {

        console.log("row",row)
        this.$prompt('请输入"' + row.realName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
        }).then(({value}) => {
          resetUserPwd(row.acctId, value).then(response => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {
        });
      },
      /** 分配角色操作 */
      handleAuthRole: function (row) {
        const userId = row.userId;
        this.$router.push("/system/user-auth/role/" + userId);
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            // this.form.merchantId =
            // this.form.roleIds = [this.form.roleIds]
            // if (this.form.userId !== undefined) {
            if (this.form.acctId) {
              updateUser(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.initPage()

              });
            } else {
              this.form.deptId = this.queryParams.deptId
              this.form.deptType = this.deptType
              addUser(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.initPage()
              });
            }
          }
        });
      },

      getCodeByRole(value) {
        console.log("value",value)
        this.rolelist.forEach(res => {
          if (res.id == value) {
            this.form.code = res.code
          }
        })
        console.log("value22",this.form.code)
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        // const userIds = row.userId || this.ids;
        const userIds = row.acctId || this.ids;
        // this.$modal.confirm('是否确认删除用户编号为"' + userIds + '"的数据项？').then(function () {
        this.$modal.confirm('是否确认删除"' + row.realName + '"的数据项？').then(function () {
          return delUser(userIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/user/export', {
          ...this.queryParams
        }, `user_${new Date().getTime()}.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      inputDeptName() {
        this.getList()
      }
    }
  };
</script>
<style>


  .el-tree-node.is-current > .el-tree-node__content {
    background-color: rgb(201, 227, 255) !important;
  }

.app-container{
    width: 100%;
    height: 100%;
    background: #f6f8f9;
  }
  .left-box{
    box-sizing: border-box;
    height: 77vh;
    padding: 15px;
    overflow-y: auto; /* 只显示垂直滚动条 */
  }
  .title-h{
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 20px;
  }
  .xzbox{
    width: 100%;
    margin: 5px auto;
    border-radius: 8px;
    height: 40px;
    box-sizing: border-box;
    padding: 0px 10px;
    display: flex;
    align-items: center;
    color: #fe8c4a;

    /*background: #99a9bf;*/
  }
  .custom-tree-box{
    margin-right: 10px;

  }
  .tab-box{
    width: 100%;
    background: #fff;
    display: flex;
    box-sizing: border-box;
    padding: 0px 50px;
  }

  .f-box{
    height: 40px;
    color: #999999;
    margin-right: 50px;
    display: flex;
    align-items: center;
    cursor: pointer;

  }
  .active{
    color: #FF9655 !important;
    border-bottom: 2px solid #FF9655 !important;
  }

  .tabder-box{
    width: 85%;
  }
</style>

