<template>
  <div class="main">
    <div class="top-box">
      <div class="my-title">客户标签管理</div>
      <div>
          <el-button class="addTask" type="primary" @click="handleCreateTag">创建标签</el-button>
          <el-button class="addTask" disabled>创建标签分类</el-button>
      </div>  
    </div>
    <div class="content">
      <div class="left">
        <div class="left_bottom">
          <el-radio-group class="header-radio" v-model="selectedTab" @input="handleChange">
            <el-radio-button label="2" :disabled="isPrivate" :class="{ 'btn-disabled': isPrivate }">企业</el-radio-button>
            <el-radio-button label="0" :disabled="isPublic" :class="{ 'btn-disabled': isPublic }">个人</el-radio-button>
            <el-radio-button label="1" :disabled="isPublic" :class="{ 'btn-disabled': isPublic }">商户</el-radio-button>
          </el-radio-group>
          <el-input v-model="searchQuery" placeholder="快速搜索关键词" clearable class="search" @keyup.enter.native="handleSearch"
            @clear="handleSearch" @blur="handleSearch"></el-input>
          <div class="left_bottom_bottom">
            <!-- <el-collapse v-model="activeName">
              <el-collapse-item v-for="(item, index) in activeList" :key="item.tabId" :title="item.tabName">
              111
            </el-collapse-item>
            </el-collapse> -->
            <el-tree :data="activeList" :props="defaultProps" @node-click="handleNodeClick" default-expand-all></el-tree>
          </div>
        </div>
      </div>
      <div class="mainlLine"></div>
      <div class="right">
        <div class="right_top" :class="ymzs == 'edit'?'spec_line':''">{{ tableTitle }}</div>
        <!-- <div class="right_topLine"></div> -->
        <div v-if="ymzs == 'home'">
          <div class="right_search">
            <el-form ref="searchForm" :model="searchForm" label-width="70px">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="标签编号">
                    <el-input v-model="searchForm.id" placeholder="请输入标签编号" clearable
                      @keyup.enter.native="handleTableSearch" @clear="handleTableSearch" @blur="handleTableSearch"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="标签名称">
                    <el-input v-model="searchForm.tabName" placeholder="请输入标签名称" clearable
                      @keyup.enter.native="handleTableSearch" @clear="handleTableSearch" @blur="handleTableSearch" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="更新人员">
                    <el-input v-model="searchForm.updateName" placeholder="请输入更新人员" clearable
                      @keyup.enter.native="handleTableSearch" @clear="handleTableSearch" @blur="handleTableSearch" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="right_table">
            <!-- <section class="operate-cnt">
              <right-toolbar @queryTable="handleRefersh" :columns="columns" style="margin-left: auto"></right-toolbar>
            </section> -->
            <el-table :data="tableData" style="width: 100%" v-loading="Loading" max-height="620">
              <el-table-column align="center" key="id" prop="id" label="标签编号" show-overflow-tooltip
                v-if="columns[0].visible">
                <template slot-scope="scope" >
                  <div :class="new Date(scope.row.endDate)<=new Date()?'unabled':''">
                    {{ scope.row.id }}
                  </div>
                </template>
                </el-table-column>
              <el-table-column align="center" key="tabName" prop="tabName" label="标签名称" show-overflow-tooltip
                v-if="columns[1].visible">
                <template slot-scope="scope" >
                  <div :class="new Date(scope.row.endDate)<=new Date()?'unabled':''">
                    {{ scope.row.tabName }}
                  </div>
                </template>
                </el-table-column>
              <el-table-column align="center" key="remark" prop="remark" label="标签说明" show-overflow-tooltip
                v-if="columns[2].visible">
                <template slot-scope="scope" >
                  <div :class="new Date(scope.row.endDate)<=new Date()?'unabled':''">
                    {{ scope.row.remark }}
                  </div>
                </template>
                </el-table-column>
              <el-table-column align="center" key="updateName" prop="updateName" label="更新人员" show-overflow-tooltip
                v-if="columns[3].visible">
                <template slot-scope="scope" >
                  <div :class="new Date(scope.row.endDate)<=new Date()?'unabled':''">
                    {{ scope.row.updateName }}
                  </div>
                </template>
                </el-table-column>
              <el-table-column align="center" key="updateTime" label="最近更新时间" show-overflow-tooltip
                v-if="columns[4].visible">
                <template slot-scope="scope" >
                  <div :class="new Date(scope.row.endDate)<=new Date()?'unabled':''">
                    {{ scope.row.updateTime.substring(0, 10) }}
                  </div>
                </template>
              </el-table-column>
              <el-table-column align="center" key="computType" prop="computType" label="更新周期" show-overflow-tooltip
                v-if="columns[5].visible">
                <template slot-scope="scope">
                  <span :class="new Date(scope.row.endDate)<=new Date()?'unabled':''">
                    {{
                      scope.row.computType == '0'?'手动执行':
                      scope.row.computType == '1'?'每日':
                      scope.row.computType == '2'?'每周':
                      scope.row.computType == '3'?'每月':
                      scope.row.computType == '4'?'每年':''
                    }}
                    
                    </span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template #header>
                  <div class="label-box">
                      操作
                    <el-tooltip
                      placement="top"
                      trigger="hover"
                      content="手动执行方式点击执行,跑批完成后会更新"
                      width="200"
                    >
                      <span class="quesiton"><i class="el-icon-question"></i></span>
                    </el-tooltip>
                  </div>
                </template>
                <template slot-scope="scope">
                  <!-- <el-button type="text" @click="handleView(scope.row)">查看</el-button> -->
                  <el-button type="text" @click="toggleOperate(scope.row)" v-if="new Date(scope.row.endDate)>new Date()">
                    {{scope.row.isStart == '1'?'停用':'启动'}}
                    </el-button>
                  <el-button type="text" @click="handleEdit(scope.row, tableTitle)">修改</el-button>
                  <el-button type="text" @click="handleRemove(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="->,total,prev,pager,next,sizes"
              :current-page="pageNum"></el-pagination>
          </div>
        </div>
        <div v-if="ymzs == 'edit'" class="view">
          <div class="view_top">
            <div class="view_topcj">{{ editTitle }}</div>
            <el-button @click="handlevieGoback">返回</el-button>
          </div>
          <div class="right_topLine"></div>
          <div class="view_main edit_three">
            <div class="three_line">标签取值设置</div>
            <el-tabs class="addTabs" v-model="editTabsValue" :editable="!isUnabled" @edit="handleTabEdit" style="margin-top: 20px;"
              @keydown.native.delete.capture.stop.self>
              <el-tab-pane v-for="(item, index) in editTabs" :key="index" :name="item.name" :label="item.title">
                <span slot="label">
                  <span v-if="index == 0" class="bqqz">标签取值</span>
                  <el-input v-model="item.tabName" class="editInput" clearable :disabled="isUnabled"></el-input>
                </span>
                <div class="rule_line">规则配置</div>
                <edit-component :content="item.obj" :editForm="editForm" :isUnabled="isUnabled" ref="editComp"></edit-component>
              </el-tab-pane>
            </el-tabs>
            <div class="drawer_two_footer">
              <el-button @click="handleEditCancel">取消</el-button>
              <el-button type="primary" @click="handleEditCommit" :disabled="isUnabled">完成</el-button>
            </div>
          </div>
          <div class="view_main_lsbb">历史版本</div>
            <div class="right_topLine"></div>
            <el-table :data="historyData" style="width: 100%">
              <el-table-column align="center" prop="roleName" label="角色"></el-table-column>
              <el-table-column align="center" prop="userName" label="用户"></el-table-column>
              <el-table-column align="center" prop="updateTime" label="修改时间"></el-table-column>
              <el-table-column align="center" prop="updateType" label="修改内容"></el-table-column>
            </el-table>
        </div>
      </div>
    </div>
    <el-drawer :title="drawerStatus == '1'?'创建标签':drawerStatus == '2'?'新增标签信息':'配置标签加工规则'" :visible.sync="addDrawer" size="50%" :wrapperClosable="false" @close="handleAddDrawerConcle">
      <div class="drawerMain" v-if="drawerStatus == '1'">
        <div class="right_topLine"></div>
        <div class="group-section" @click="handleStasTag('属性类')">
          <div class="group-section-left"><i icon-class="rule" class="el-icon-s-custom" /></div>
          <div class="group-text">
            <h3>自定义取值标签</h3>
            <p>
              自定义不同的客户属性规则，对满足规则的客户打上标签，形成不同的客户分层和分类，例如：未办理信用卡
            </p>
          </div>
        </div>
        <div class="group-section" @click="handleStasTag('统计类')">
          <div class="group-section-left"><i icon-class="rule" class="el-icon-s-data" /></div>
          <div class="group-text">
            <h3>统计指标标签</h3>
            <p>将客户指定时间周期内某些行为发生次数的统计指标作为标签，形成不同的客户分层和分类，例如：近三月客户用信次数。</p>
          </div>
        </div>
        <div class="drawer_one_footer">
          <el-button @click="handleAddDrawerConcle">取消</el-button>

        </div>
      </div>
      <div class="drawerMain" v-if="drawerStatus == '2'">
        <!-- <div class="top_title">新增标签信息</div> -->
        <div class="right_topLine"></div>
        <div class="drawer_two_main">
          <el-form ref="drawerTwoForm" :model="drawerTwoForm" :rules="drawerTwoFormRules" label-width="120px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="标签名称" prop="tabName">
                  <el-input v-model="drawerTwoForm.tabName" placeholder="请输入标签名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="英文名称" prop="tabId">
                  <el-input v-model="drawerTwoForm.tabId" placeholder="请输入标签英文名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="标签所属分类" prop="parentId">
                  <!-- :multiple="true" -->
                  <!-- <treeselect class="input-box" v-model="drawerTwoForm.parentId" :options="typeList" placeholder="请选择"
                    :flat="true">
                  </treeselect> -->
                  <el-select v-model="drawerTwoForm.parentId">
                    <el-option v-for="item in parentIdList" :key="item.id" :label="item.label"
                      :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="加工类型" prop="computType">
                  <el-radio-group v-model="drawerTwoForm.computType">
                    <el-radio label="0">手动执行</el-radio>
                    <el-radio label="1">周期执行</el-radio>
                  </el-radio-group>

                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label-width="0">
                  <el-select filterable v-model="drawerTwoForm.zxzq"
                    v-if="drawerTwoForm.computType != '0' && drawerTwoForm.computType != ''" @change="handleChangeZxzq">
                    <el-option v-for="item in dateList" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="到期时间" prop="endTime">
                  <el-date-picker v-model="drawerTwoForm.endTime" type="date" value-format="yyyy-MM-dd"
                    :picker-options="pickdqDateOption">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="权限设置" prop="authType">
                  <el-row>
                    <el-col>
                      <el-radio-group v-model="drawerTwoForm.authType">
                        <el-radio label="1">仅自己可见</el-radio>
                        <el-radio label="2">指定人员可见</el-radio>
                        <el-radio label="3">所有人可见</el-radio>
                      </el-radio-group>
                    </el-col>
                  </el-row>

                </el-form-item>

              </el-col>
            </el-row>
            <el-row v-if="drawerTwoForm.authType == '2'">
              <el-col :span="24">
                <el-form-item label="">
                  <section class="user-info">
                    <span>归属机构</span>
                    <treeselect ref="orgTree" size="small" :multiple="true" v-model="userDeptList" :options="deptOptions"
                      placeholder="请选择" :show-count="true" noOptionsText="暂无数据" noResultsText="暂无数据" :limit="2"
                      :limit-text="(count) => `+${count}`" @select="(node) => onDeptTreeSelect(node)"
                      @deselect="clearTreeSelect" @open="onOrgTreeFocus" :flat="false" />
                  </section>
                  <section class="user-info">
                    <span>客户经理</span>
                    <el-select @focus="onClientManagerFocus" ref="clientManager" v-model="drawerTwoForm.authUser" multiple
                      :multiple-limit="0" size="small" filterable placeholder="请选择" class="input-box">
                      <el-option v-for="option in managerOptions" :key="option.userId"
                        :label="`${option.deptName}-${option.userName}-${option.nickName}`"
                        :value="option.userName"></el-option>
                    </el-select>
                  </section>
                  <!-- <el-select v-model="drawerTwoForm.authUser" @focus="handleSelectUser" multiple filterable>
                    <el-option v-for="item in personList" :key="item.value" :label="item.label"
                      :value="item.value"></el-option>
                  </el-select> -->
                </el-form-item>

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

            <el-row>
              <el-col :span="24">
                <el-form-item label="标签说明" prop="remark">
                  <el-input v-model="drawerTwoForm.remark" placeholder="请输入标签说明" type="textarea" rows="10" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="drawer_two_footer">
            <el-button @click="handleAddDrawerConcle">取消</el-button>
            <el-button @click="handleToOne">上一步</el-button>
            <el-button type="primary" @click="handleToThree">下一步</el-button>
          </div>
        </div>
      </div>
      <div class="drawerMain_three" v-if="drawerStatus == '3'">
        <!-- <h2>配置标签的加工规则</h2> -->
        <!-- <el-divider></el-divider> -->
        <div class="right_topLine"></div>
        <div class="three-content">
          <div class="three_line">标签取值设置</div>
          <el-tabs v-model="addTabsValue" editable @edit="handleTabAdd" @keydown.native.delete.capture.stop.self
            class="addTabs">
            <el-tab-pane v-for="(item, index) in addTabs" :key="item.name" :name="item.name" :label="item.title">
              <span slot="label">
                <span v-if="index == 0" class="bqqz">标签取值</span>
                <el-input v-model="item.title" clearable class="tabTop"></el-input>
              </span>
              <div class="rule_line">规则配置</div>
              <tag-component :is="item.content" :obj="item.obj"></tag-component>
            </el-tab-pane>
          </el-tabs>
          <div class="drawer_two_footer">
            <el-button @click="handleAddDrawerConcle">取消</el-button>
            <el-button @click="handleToTwo">上一步</el-button>
            <el-button type="primary" @click="handleOver">完成</el-button>
          </div>
          </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import tagComponent from './compontent/tagComponent.vue'
import { mapGetters } from 'vuex'
import editComponent from './compontent/editComponent.vue'
import { listTopTab, listTab, listPot, deptUser, addTabs, getTabDetail, removeTabDetail, editTabs,operateUpdate } from '@/api/tag/tagList.js'
import { getUserProfile } from '@/api/grid/anchor.js'
import { Message } from "element-ui";
import { getDeptTree } from '@/api/grid/address/tree.js'
import { getUserListByDeptIds } from "@/api/grid/region.js";
import { isEmpty } from "lodash";
export default {
  components: {
    tagComponent,
    editComponent
  },
  data() {
    var validateTabId = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入英文名称'))
      }
      if (/[\u4E00-\u9FA5]/g.test(value)) {
        callback(new Error('不能输入中文'))
      } else {
        callback()
      }
    }
    return {
      outType: '',
      tabValue: '',
      selectedTab: '0',
      searchQuery: '',
      activeName: '',
      activeList: [],
      defaultProps: {
        children: 'child',
        label: 'tabName'
      },

      ymzs: 'home',
      editId: '',
      searchForm: {
        id: '',
        tabName: '',
        updateName: ''
      },
      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 },
      ],
      tableData: [],
      historyData: [],
      Loading: false,
      total: 0,
      pageSize: 10,
      pageNum: 1,
      addDrawer: false,
      drawerStatus: '1',
      drawerTwoForm: {
        tabName: '',
        tabId: '',
        parentId: null,
        computType: '',
        zxzq: '',
        endTime: '',
        authType: '',
        authUser: [],
        remark: ''
      },
      typeList: [

      ],
      parentIdList: [],
      dateList: [
        { label: '每日', value: '1' },
        { label: '每周', value: '2' },
        { label: '每月', value: '3' },
        { label: '每年', value: '4' },
      ],
      editTypeList: ['属性指标', '统计指标'],
      personList: [],
      drawerTwoFormRules: {
        tabName: [{ required: true, message: "标签名称不能为空", trigger: 'blur' }],
        tabId: [{ validator: validateTabId, trigger: 'blur' }, { required: true, message: "英文名称不能为空" }],
        parentId: [{ required: true, message: "请选择标签所属分类" }],
        computType: [{ required: true, message: "请选择加工类型", trigger: 'change' }],
        zxzq: [{ required: true, message: "请选择加工类型", trigger: 'change' }],
        endTime: [{ required: true, message: "请选择到期时间", trigger: 'change' }],
        authType: [{ required: true, message: "请选择权限设置", trigger: 'change' }],
        authUser: [{ required: true, message: "请选择指定人员", trigger: 'change' }],
      },
      addTabsValue: '1',
      addTabs: [
        {
          title: '高',
          name: '1',
          content: tagComponent,
          obj: { ruleConditionsList: [{ selectTitle: '', relation: '且', num: 0, relationItem: '或', itemNum: 0, ruleList: [{ leftValue: '', expression: '', rightValue: '', isShow: 'select' }] }], }
        }
      ],
      tabIndex: 1,
      viewRuleConditionsList: [],
      viewList: [],
      rowLeftList: [],
      expressionList: [
        { label: '>', value: '1' },
        { label: '>=', value: '2' },
        { label: '=', value: '3' },
        { label: '<=', value: '4' },
        { label: '<', value: '5' },
        { label: '!=', value: '6' },
      ],
      rowRightList: [],
      tableTitle: '',
      tableId: '',
      deptNowId: '',
      tabNameList: [],
      editTabsValue: '1',
      editTabs: [

      ],
      editForm: {},
      deptOptions: [],
      userDeptList: [],
      checkedArr: [], // 选择的机构ID
      managerOptions: [],
      viewTitle: '',
      editTitle: '',
      editNameLength: 0,
      pickdqDateOption: {
        disabledDate(time) {
          return time.getTime() <= Date.now()
        }
      },
      isUnabled:false,
    }
  },
  computed: {
    ...mapGetters(['roles']),
    //对公
    isPublic() {
      return this.roles.includes('headPublic')
    },
    //对私
    isPrivate() {
      return this.roles.includes('headPrivate')
    },

  },
  created() {
    if (this.isPublic) {
      this.selectedTab = '2'
    } else if (this.isPrivate) {
      this.selectedTab = '0'
    } else {
      this.selectedTab = '0'
    }
    this.getUser()
    this.initlistTopTab()
    this.initBqssSelectTab()
    this.initListpot()
    this.getDeptTreeSelect()
  },
  methods: {
    getDeptTreeSelect() {
      getDeptTree().then((response) => {
        this.deptOptions = response.data
      })
    },
    // 选择归属机构
    onDeptTreeSelect(node) {
      const { children = [] } = node;
      const childrenArr = children.map((child) => child.id);
      this.checkedArr = [
        ...new Set([
          ...this.checkedArr,
          // ...this.userChecked,
          node.id,
          ...childrenArr,
        ]),
      ];
      this.fetchSelectOptions(this.checkedArr);
    },
    // 取消勾选归属机构
    clearTreeSelect(node) {
      const index = this.checkedArr.findIndex((id) => id === node.id);
      if (index > -1) {
        this.checkedArr.splice(index, 1);
      }
      const { children = [] } = node;
      if (children.length > 0) {
        children.map((child) => {
          const index = this.checkedArr.findIndex((id) => id === child.id);
          if (index > -1) {
            this.checkedArr.splice(index, 1);
          }
        });
      }
    },
    fetchSelectOptions(deptIds) {
      if (isEmpty(deptIds)) {
        return (this.managerOptions = []);
      }
      getUserListByDeptIds({ deptIds: deptIds }).then((response) => {
        this.managerOptions = response.data;
      });
    },
    onOrgTreeFocus() {
      // this.$refs.clientManager.blur()
    },
    onClientManagerFocus() {
      // this.$refs.orgTree.blurInput()
    },
    initListpot() {
      listPot('').then(res => {
        this.rowLeftList = res.data
      })
    },
    initlistTopTab() {
      const params = {
        tabTypeName: this.searchQuery,
        custType: this.selectedTab
      }
      listTopTab(params).then(res => {
        if (res.data.length > 0) {
          this.tableTitle = res.data[0].tabName
          this.activeList = res.data
        } else {
          this.activeList = []
        }
      })
    },
    initBqssSelectTab() {
      const params = {
        tabTypeName: '',
        custType: this.selectedTab
      }
      listTopTab(params).then(res => {
        if (res.data.length > 0) {
          this.typeList = res.data.map(item => {
            return {
              label: item.tabName,
              id: item.tabId,
              isDisabled: true,
              children: item.child ? item.child.map(el => {
                return {
                  label: el.tabName,
                  id: el.tabId,
                }
              }) : []
            }
          })
        } else {
          this.typeList = []
        }
        console.log(this.typeList, 'this.typeList')
      })
    },
    handleSearch() {
      this.initlistTopTab()
    },
    handleChange() {
      this.initlistTopTab()
      this.initBqssSelectTab()
    },
    handleNodeClick(data) {
      if (data.parentId != -1) {
        this.tableTitle = data.tabName
        this.tableId = data.tabId
        this.initTableData()
      }
    },
    initTableData() {
      const params = {
        custType: this.selectedTab,
        parentId: this.tableId,
        id: this.searchForm.id,
        tabName: this.searchForm.tabName,
        updateName: this.searchForm.updateName,
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        isAsc: 'descending',
        orderByColumn: 'updateTime'
      }
      listTab(params).then(res => {
        this.tableData = res.data
      })
    },
    handleTableSearch() {
      if(this.searchForm.id && !Number(this.searchForm.id) && this.searchForm.id!='0'){
        Message.warning('标签编号只能输入数字');
        return;
      }
      this.initTableData()
    },
    handleRefersh() { },
    handleSizeChange(newSize) {
      this.pageSize = newSize
      this.initTableData()
    },
    handleCurrentChange(newPage) {
      this.pageNum = newPage
      this.initTableData()
    },
    handleView(row) {
      this.viewTitle = row.tabName
      getTabDetail(row.id).then(res => {
        console.log(res, 'ssssssss')
        this.historyData = res.data.custTabEditHis
        this.tabNameList = res.data.tabEnums.map(item => {
          return item.tabName
        })
        let arr = res.data.tabEnums.map(item => {
          return item.treelist
        })
        let list = arr.map(item => { return JSON.parse(item) })
        console.log(list, 'listlist')
        this.viewList = list
        this.viewRuleConditionsList = list[0].filter(item => item.ruleList[0].leftValue != '')
      })
      this.ymzs = 'view'
    },
    handleViewTab(index) {
      this.viewRuleConditionsList = this.viewList[index].filter(item => item.ruleList[0].leftValue != '')
    },
    handleEdit(row, tableTitle) {
      if(new Date(row.endDate)<=new Date()){
        this.isUnabled = true;
      }else{
        this.isUnabled = false;
      }
      this.editTitle = row.tabName
      let str = []
      for (let i = 0; i < this.typeList.length; i++) {

        for (let j = 0; j < this.typeList[i].children.length; j++) {

          if (this.typeList[i].children[j].label == tableTitle) {

            str = this.typeList[i].label
          }
        }
      }
      console.log(str, 'str')
      if (str == '属性类') {
        this.outType = '3'
      } else if (str == '统计类') {
        this.outType = '1'
      }
      this.editForm = row
      this.ymzs = 'edit'
      this.editId = row.id
      getTabDetail(row.id).then(res => {
        this.historyData = res.data.custTabEditHis
        let arr = res.data.tabEnums.map(item => {
          return {
            tabName: item.tabName,
            list: JSON.parse(item.treelist)
          }
        })

        this.editTabs = arr.map((item, index) => {
          return {
            tabName: item.tabName,
            title: item.tabName,
            name: String(index + 1),
            obj: { ruleConditionsList: item.list }
          }
        })
        this.editTabsValue = this.editTabs[0].name
        this.editNameLength = this.editTabs.length
        console.log(this.editTabs, 'this.editTabs')
      })
    },
    handleRemove(row) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeTabDetail(row.id).then(res => {
          if (res.code == 200) {
            Message.success('删除成功')
            this.initTableData()
          }
        })
      }).catch(() => {
        Message.info('已取消')
      })
    },
    handlevieGoback() {
      this.ymzs = 'home'
    },
    handleCreateTag() {
      this.addDrawer = true
      this.drawerStatus = 1
    },
    handleStasTag(title) {
      if (title == '统计类') {
        this.outType = '1'
        let list = []
        list = this.typeList.filter(item => item.label == title)
        this.parentIdList = list.length > 0 ? list[0].children : []
      } else if (title == '属性类') {
        this.outType = '3'
        let list = []
        list = this.typeList.filter(item => item.label == title)
        this.parentIdList = list.length > 0 ? list[0].children : []
        console.log(this.parentIdList, 'this.parentIdList')
      }
      this.drawerStatus = 2
    },
    handleChangeZxzq(val) {

      // this.drawerTwoForm.computType = val
    },
    getUser() {
      getUserProfile().then(res => {
        this.deptNowId = res.data.dept.deptId
      })
    },
    handleSelectUser() {
      const params = {
        deptId: this.deptNowId
      }
      deptUser(params).then(res => {

        this.personList = res.data.users.map(item => {
          return {
            label: `${item.nickName}-${item.userName}`,
            value: item.userName
          }
        })
      })
    },
    handleToOne() {
      this.drawerStatus = 1
    },
    handleToThree() {
      console.log(this.drawerTwoForm)
      this.$refs.drawerTwoForm.validate((valid) => {
        if (valid) {
          this.drawerStatus = 3
        } else {
          return false
        }
      })
    },
    handleToTwo() {
      this.drawerStatus = 2
    },
    handleTabAdd(targename, action) {
      if (action === 'add') {
        let newTabName = ++this.tabIndex + ''
        let newObj = { ruleConditionsList: [{ selectTitle: '', relation: '且', num: 0, relationItem: '或', itemNum: 0, ruleList: [{ leftValue: '', expression: '', rightValue: '', isShow: 'select' }] }], }
        this.addTabs.push({
          title: '',
          name: newTabName,
          content: tagComponent,
          obj: newObj
        })
        this.addTabsValue = newTabName
      }
      if (action === 'remove') {
        let tabs = this.addTabs
        let activeName = this.addTabsValue
        if (activeName == targename) {
          tabs.forEach((tab, index) => {
            if (tab.name === targename) {
              let nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.name
              }
            }
          })
        }
        this.addTabsValue = activeName
        this.addTabs = tabs.filter(tab => tab.name !== targename)
      }
    },
    initPotRelation(arr) {

      let strList = []

      let data = arr.map(item => { return item.ruleList })
      let relationList = arr.map(item => {
        if (item.relation == '且') {
          return 'and'
        } else {
          return 'or'
        }
      })
      let relationItemList = arr.map(item => {
        if (item.relationItem == '且') {
          return 'and'
        } else {
          return 'or'
        }
      })
      data.pop()
      for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < data[i].length; j++) {
          strList.push(data[i][j].leftValue)

        }
      }
      relationList.shift()
      console.log(relationList, 'relationList')
      console.log(relationItemList, 'relationItemList')
      let one1 = []
      let one2 = []
      let one3 = []

      if (data[0] && data[0].length > 0) {
        one1 = strList.slice(0, data[0].length);
      }
      if ((data[0] && data[0].length > 0) && (data[1] && data[1].length > 0)) {
        one2 = strList.slice(data[0].length, data[0].length + data[1].length);
      }
      if ((data[0] && data[0].length > 0) && (data[1] && data[1].length > 0) && (data[2] && data[2].length > 0)) {
        one3 = strList.slice(data[0].length + data[1].length, data[0].length + data[1].length + data[2].length);
      }

      let str1 = ''
      let str2 = ''
      let str3 = ''
      for (let i = 0; i < one1.length; i++) {
        str1 += `[${one1[i]}]` + relationItemList[0]
      }
      if (one2.length > 0) {
        for (let i = 0; i < one2.length; i++) {
          str2 += `[${one2[i]}]` + relationItemList[1]
        }
      }
      if (one3.length > 0) {
        for (let i = 0; i < one3.length; i++) {
          str3 += `[${one3[i]}]` + relationItemList[2]
        }
      }
      let strOne = []
      let strTwo = []
      let strTree = []
      if (str1[str1.length - 1] == 'd') {

        strOne = str1.slice(0, -3)
      } else {
        strOne = str1.slice(0, -2)
      }
      if (str2[str2.length - 1] == 'd') {

        strTwo = str2.slice(0, -3)
      } else {
        strTwo = str2.slice(0, -2)
      }
      if (str3[str3.length - 1] == 'd') {

        strTree = str3.slice(0, -3)
      } else {
        strTree = str3.slice(0, -2)
      }
      if (strOne.length > 0 && strTwo.length == 0) {
        return `(${strOne})`
      }
      if (strOne.length > 0 && strTwo.length > 0 && strTree.length == 0) {
        return `(${strOne})${relationList[0]}(${strTwo})`
      }
      if (strOne.length > 0 && strTwo.length > 0 && strTree.length > 0) {
        return `(${strOne})${relationList[0]}(${strTwo})${relationList[1]}(${strTree})`
      }


    },

    handleOver() {
      console.log(this.addTabs,this.drawerTwoForm)

      let arr = this.addTabs.map((item, index) => {
        let ruleConditionsList = item.obj.ruleConditionsList.map(i=>{
          return {
            ...i,
            ruleList:i.ruleList.map(m=>{
              return {
                ...m,
                isUnEquals:m.expression == '6'?'1':'0'
              }
            })
          }
        })
        return {
          tabName: item.title,
          treeList: JSON.stringify(ruleConditionsList),
          potRelation: ruleConditionsList.map(el => {
            return {
              ruleList: el.ruleList,
              relation: el.relation,
              relationItem: el.relationItem,
            }
          }),
          list: ruleConditionsList.map(item => item.ruleList)
        }
      })
      console.log(arr)
      let list = arr.map(item => {
        return {
          tabName: item.tabName,
          treeList: item.treeList,
          potRelation: this.initPotRelation(item.potRelation),
          list: (item.list.flat()).filter((el) => el.leftValue != '')
        }
      })
      for (let i = 0; i < list.length; i++) {
        if (list[i].tabName == '') {
          return Message.warning('标签取值不能为空')
        }
      }
      console.log(list, 'listlistlist', this.drawerTwoForm)
      let list1 = list.map(item => {
        return {
          tabName: item.tabName,
          potRelation: item.potRelation,
          treeList: item.treeList,

          potDetails: item.list.map(el => {

            if (el.isShow == "input") {
              return {
                potId: el.leftValue,
                tabThresholdRule: el.expression,
                tabThreshold: el.tabThreshold,
                tabThresholdType: '1',
              }
            } else {
              return {
                potId: el.leftValue,
                tabThresholdType: '3',
                enumVal: el.rightValue,
                isUnEquals:el.expression == '6'?'1':'0'
              }
            }
          })
        }
      })
      const params = {
        custType: this.selectedTab,
        tabName: this.drawerTwoForm.tabName,
        tabId: this.drawerTwoForm.tabId,
        parentId: this.drawerTwoForm.parentId,
        computType: this.drawerTwoForm.computType == '0' ?'0':this.drawerTwoForm.zxzq,
        endTime: this.drawerTwoForm.endTime,
        authType: this.drawerTwoForm.authType,
        authUser: this.drawerTwoForm.authUser.length > 0 ? this.drawerTwoForm.authUser.join('|') : '',
        remark: this.drawerTwoForm.remark,
        tabThresholdType: this.outType,
        tabPotAddDTOS: list1,

      }
      console.log(params, 'params',list1);
      if (params.tabPotAddDTOS[0].potDetails.length < 1) {
        Message.warning('请至少添加一个标签')
      } else {
        addTabs(params).then(res => {
          if (res.code == 200) {
            Message.success('创建成功')
            this.addDrawer = false
            this.drawerStatus = {}
            this.initTableData()
            this.initlistTopTab()
            this.handleAddDrawerConcle()
          }
        })
      }

    },
    handleAddDrawerConcle() {
      this.addDrawer = false
      this.drawerTwoForm = {}
      this.userDeptList = []
      this.drawerTwoForm.authUser = []
      this.addTabs = [
        {
          title: '高',
          name: '1',
          content: tagComponent,
          obj: { ruleConditionsList: [{ selectTitle: '', relation: '且', num: 0, relationItem: '或', itemNum: 0, ruleList: [{ leftValue: '', expression: '', rightValue: '', isShow: 'input' }] }], }
        }
      ]
    },
    handleTabEdit(targename, action) {

      if (action === 'add') {
        let newTabName = ++this.editNameLength + ''
        let newObj = { ruleConditionsList: [{ selectTitle: '', relation: '且', num: 0, relationItem: '或', itemNum: 0, ruleList: [{ leftValue: '', expression: '', rightValue: '', isShow: 'select' }] }], }
        this.editTabs.push({
          title: '',
          name: newTabName,
          content: editComponent,
          obj: newObj
        })
        this.editTabsValue = newTabName
      }
      if (action === 'remove') {
        let tabs = this.editTabs
        let activeName = this.editTabsValue
        if (activeName == targename) {
          tabs.forEach((tab, index) => {
            if (tab.name === targename) {
              let nextTab = tabs[index + 1] || tabs[index - 1]
              if (nextTab) {
                activeName = nextTab.name
              }
            }
          })
        }
        this.editTabsValue = activeName
        this.editTabs = tabs.filter(tab => tab.name !== targename)
      }
    },
    handleEditCancel() {
      this.ymzs = 'home'
    },
    handleEditCommit() {
      console.log(this.editTabs, 'editTabseditTabs',this.$refs.editComp[0].drawerTwoForm)
      const {computType,zxzq,endTime} = this.$refs.editComp[0].drawerTwoForm;
      let arr = this.editTabs.map((item, index) => {
        let ruleConditionsList = item.obj.ruleConditionsList.map(i=>{
          return {
            ...i,
            ruleList:i.ruleList.map(m=>{
              return {
                ...m,
                isUnEquals:m.expression == '6'?'1':'0'
              }
            })
          }
        })
        return {
          tabName: item.tabName ? item.tabName : '',
          treeList: JSON.stringify(ruleConditionsList),
          potRelation: ruleConditionsList.map(el => {
            return {
              ruleList: el.ruleList,
              relation: el.relation,
              relationItem: el.relationItem,
            }
          }),
          list: ruleConditionsList.map(item => item.ruleList)
        }
      })
      console.log(arr)
      let list = arr.map(item => {
        return {
          tabName: item.tabName,
          treeList: item.treeList,
          potRelation: this.initPotRelation(item.potRelation),
          list: (item.list.flat()).filter((el) => el.leftValue != '')
        }
      })
      for (let i = 0; i < list.length; i++) {
        if (list[i].tabName == '') {
          return Message.warning('标签取值不能为空')
        }
      }
      console.log(list, 'listlistlist')
      let list1 = list.map(item => {
        return {
          tabName: item.tabName,
          potRelation: item.potRelation,
          treeList: item.treeList,
          potDetails: item.list.map(el => {

            if (el.isShow == "input") {
              return {
                potId: el.leftValue,
                tabThresholdRule: el.expression,
                tabThreshold: el.rightValue,
                tabThresholdType: '1',
              }
            } else {
              return {
                potId: el.leftValue,
                tabThresholdType: '3',
                enumVal: el.rightValue,
                isUnEquals:el.expression == '6'?'1':'0'
              }

            }

          })
        }
      })
      const params = {
        id: this.editId,
        tabAddDTO: {
          custType: this.editForm.custType,
          tabName: this.editForm.tabName,
          tabId: this.editForm.tabId,
          parentId: this.editForm.parentId,
          computType: computType == '0'?'0':zxzq,
          endTime:endTime,
          authType: this.editForm.authType,
          authUser: this.editForm.authUser,
          remark: this.editForm.remark,
          tabThresholdType: this.outType,
          tabPotAddDTOS: list1
        },

      }
      console.log(params, 'paramsparams',list1)
      editTabs(params).then(res => {
        console.log(res, 'ssssssssssss')
        if (res.code == 200) {
          Message.success('修改成功')
          this.ymzs = 'home'
          this.editTabs = []
          this.initTableData()
          this.initlistTopTab()
        }
      })
    },
    // 启动停用
    toggleOperate(row){
      operateUpdate({
        id: row.id,
        status:row.isStart == '1'?'0':'1'
      }).then(res=>{
        if (res.code == 200) {
          Message.success(`${row.isStart == '1'?'停用':'启动'}成功`)
          this.initTableData()
        }
      })
    },
  },
}
</script>
<style lang="scss" scoped>
.main {
  background-color: #ffffff;
  overflow: hidden;
  box-shadow: 0 3px 8px 0 #00000017;
  border-radius: 16px 16px 0 0;
  // display: flex;
  .top-box{
    display: flex;
    justify-content: space-between;
    align-items: center;
    .my-title{
      font-size: 16px;
      color:rgba(38,38,38,1);
      margin-left: 16px;
    }
  }
  .content{
    display: flex;
    border-top: 1px solid #ddd;
    margin-top: 5px;
  }
  ::v-deep .el-drawer__header{
      color:rgba(16,16,16,1);
      margin-bottom: 16px;
      padding-top: 10px;
    }
}

.left {
  width: 25%;
}

.left_top {
  padding: 20px;

  ::v-deep .el-button {
    width: 100%;
    height: 43px;
  }

  .left_top_btn {
    margin-top: 20px;
  }
}

.mainlLine {
  width: 1px;
  background-color: #ddd;
  // margin: 10px 0;
}

.right {
  width: 75%;
  .spec_line{
    border-bottom: 1px solid #ccc;
    margin: 0 20px;
    padding: 0 0;
  }
}

.left_top_line {
  height: 1px;
  background-color: #ccc;
}

.left_bottom {
  padding: 20px;
  padding-top: 10px;

  ::v-deep .el-radio-group {
    width: 100%;
  }

  ::v-deep .el-radio-button {
    width: 33.33% !important;
  }

  ::v-deep .el-radio-button__inner {
    width: 100% !important;
  }

  ::v-deep .search {
    margin: 15px 0;
  }

  ::v-deep .el-input__inner {
    border-radius: 20px;
  }
}

.right {
  margin-left: 20px;
}

.right_top {
  line-height: 50px;
  color:rgba(38,38,38,1);
  padding:0 20px;
}
.edit-title{

}

.right_topLine {
  height: 1px;
  background-color: #ccc;
}
// .spec_line{
//   padding: 0 50px;
// }

.right_search {
  margin: 20px 0;

  ::v-deep .el-input {
    width: 200px;
  }
}

::v-deep .el-pagination {
  margin-top: 15px;
}

.drawerMain {
  .group-section {
    margin: 30px;
    height: 114px;
    cursor: pointer;
    align-items: center;
    gap: 10px;
    padding: 10px;
    border: 1px solid #cccccc;
    border-radius: 3px;
    display: flex;

    .group-text {
      flex-grow: 1;

      h3 {
        font-weight: 600;
        margin: 0;
        font-size: 16px;
        margin-bottom: 5px;
      }

      p {
        margin: 0;
        font-size: 12px;
        line-height: 20px;
        font-weight: 400;
        letter-spacing: 0;
        text-align: justify;
        color: #838282;
      }
    }
  }

}

.drawerMain_three {
  // margin: 30px;

  ::v-deep .el-input {
    width: 130px;
  }

  ::v-deep .el-tabs__item {
    padding: 0 10px 0 0 !important;
  }
  .three-content{
    padding: 0 20px;
    margin-top: 10px;
    .three_line {
      margin-bottom: 30px;
      position: relative;
      &::before {
        position: absolute;
        top: 50%;
        transform: translatey(-50%);
        left: -6px;
        content: '';
        width: 3px;
        background-color: #4886f8;
        height: 16px;
        border-radius: 2px;
      }
    }
    .rule_line {
      // margin-bottom: 30px;
      position: relative;
      margin-left: 6px;
      &::before {
        position: absolute;
        top: 50%;
        transform: translatey(-50%);
        left: -5px;
        content: '';
        width: 3px;
        background-color: #4886f8;
        height: 16px;
        border-radius: 2px;
      }
    }

  }
}
.edit_three{
  .three_line {
      // margin-bottom: 30px;
      margin-top: 10px;
      position: relative;
      margin-left: 6px;
      &::before {
        position: absolute;
        top: 50%;
        transform: translatey(-50%);
        left: -6px;
        content: '';
        width: 3px;
        background-color: #4886f8;
        height: 16px;
        border-radius: 2px;
      }
    }
    .rule_line {
      // margin-bottom: 30px;
      position: relative;
      margin-left: 6px;
      &::before {
        position: absolute;
        top: 50%;
        transform: translatey(-50%);
        left: -5px;
        content: '';
        width: 3px;
        background-color: #4886f8;
        height: 16px;
        border-radius: 2px;
      }
    }
}


.mzti_box {
  width: 100%;
}

.view_main_bqqu_left {
  width: 100px;
}

.top_title {
  font-size: 20px;
  margin: 20px;
}

.group-section-left {
  font-size: 50px;
  color: rgb(147, 210, 243);
}

.drawer_two_main {
  padding: 30px;

  ::v-deep .el-select {
    width: 100%;
  }
}

.drawer_two_footer {
  margin-top: 50px;
  text-align: right;
}

.drawer_one_footer {
  margin-top: 20px;
  text-align: right;
  padding-right: 30px;
}

.bqqz {
  display: inline-block;
  width: 80px;
  font-size: 16px;
  margin: 0 15px 0 5px;
}

.view {
  margin: 20px;
  margin-top: 0;
}

.view_top {
  display: flex;
  align-items: center;
  margin: 7px 0;
  justify-content: space-between;
}

.view_topcj {
  font-size: 20px;
  // margin: 5px 0;
}

.view_main_bqqu {
  display: flex;
  align-items: center;
  margin: 20px 0;
}

.view_main_lsbb {
  margin: 20px 0;
}

.lsbb_main {
  margin-top: 20px;

  li {
    padding: 15px;
  }
}

.ruleBox {
  display: flex;
  margin-top: 15px;
}

.ruleBox_left {
  padding-top: 10px;
  width: 100px;
  text-align: right;
}


.ruleBox_line_box {
  display: flex;
}

.ruleBox_line {
  width: 3px;
  background-color: #ccc;
  margin-left: 20px;
}

.ruleBox_line_left {
  width: 16px;
  color: rgb(64, 149, 229);
}

.relation {
  cursor: pointer;

}

.ruleBox_right {
  padding-left: 30px;
  width: 100%;
  padding-bottom: 30px;
}

.ruleSelect_top:hover .ruleSelect_right_icon {
  display: block;
}

.ruleSelect_right_icon {
  margin-left: 15px;
  cursor: pointer;
  display: none;
}

.ruleTitle {
  margin-top: 20px;
  font-size: 14px;
  color: #ccc;
}

.ruleSelect_top {
  display: flex;
  padding-left: 10px;
  align-items: center;
}

.ruleSelect_left {
  width: 15px;
  height: 15px;
  text-align: center;
  line-height: 13px;
  background-color: rgb(64, 149, 229);
  color: #fff;
}

.editInput {
  width: 100px;
}

.ruleSelect_right {
  margin-left: 15px;
}

.ruleSelect_main {
  margin-top: 15px;
  display: flex;
}

.line_box {
  display: flex;
  width: 15px;
  flex-direction: column;
}

.line_text {

  margin: 5px 0 5px 6px;
  color: rgb(64, 149, 229);
  cursor: pointer;
  width: 22px;
  height: 22px;
  text-align: center;
  line-height: 21px;
  border: 1px solid #ccc;
  border-radius: 50%;
}

.ruleSelect_main_left {
  width: 3px;
  margin-left: 15px;
  height: 100%;
  background-color: #ccc;
}

.ruleSelect_main_right {
  width: 100%;
  margin-left: 23px;
}

.addIcon {
  line-height: 40px;
  margin-left: 15px;
  display: none;
}

.ruleSelect_main_right_item:hover .addIcon {
  display: block;
}

.ruleSelect_main_right_item {
  height: 40px;
  margin-top: 10px;
}

.btn-disabled {
  ::v-deep .el-radio-button__inner {
    background-color: #e7e7e7;
  }
}

.ruleIcon {
  font-size: 16px;
  cursor: pointer;
}

.user-info {
  margin-bottom: 5px;
  margin-left: 26px;
  display: flex;
  align-items: center;

  ::v-deep .vue-treeselect__control {
    width: 320px !important;
    height: 32px;
  }

  span {
    width: 70px !important;
    margin-right: 10px;
    font-size: 14px;
    color: #606266;

    &::before {
      content: "*";
      left: -3px;
      color: #ff4d42;
      position: relative;
      top: 2px;
    }
  }

  .input-box {
    width: 320px !important;
  }
}

.addTabs {
  ::v-deep .el-tabs__new-tab {
    background-color: #4095e5;
  }

}
  ::v-deep .el-tabs__active-bar {
    height: 5px;
}
.unabled{
  color: #ddd;
}
.label-box {
  display: inline-block;
  position: relative;
}

.quesiton {    
  display: block;
  font-size: 13px;
  color: #b9b9b9;
  position: absolute;
  right: -14px;
  top: -5px;
}
</style>