<template>
  <div class="categorySet-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <div ref="headerBar">
        <a-page-header :ghost="false" :backIcon="false" class="header-bar">
          <!-- 自定义的二级文字标题 -->
          <template slot="subTitle">
            <a id="salesEdit-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
            <span class="subTitle-word text-overflow" style="max-width:300px;margin-left:15px;">用户姓名：{{ infoObj.userName?infoObj.userName:'--' }}</span>
          </template>
        </a-page-header>
      </div>
      <a-card size="small" :bordered="false" class="categorySet-cont">
        <div>
          <a-tabs v-model="activeKeyVal" @change="handleTabs" id="settingsIndex-tabs">
            <a-tab-pane key="1" tab="设置管辖区域" v-if="infoObj.allDealerFlag && infoObj.allDealerFlag!=1">
              <div class="areaSet-wrap">
                <div class="table-page-search-wrapper newTableSearchName" >
                  <a-form layout="inline" id="settingsIndex-form" @keyup.enter.native="$refs.table.refresh(true)">
                    <a-row :gutter="15">
                      <a-col :md="6" :sm="24">
                        <a-form-item label="所在区域/分区">
                          <subarea id="settingsIndex-subarea" ref="subarea" @change="subareaChange"></subarea>
                        </a-form-item>
                      </a-col>
                      <a-col :md="6" :sm="24">
                        <a-form-item label="经销商名称">
                          <a-input id="settingsIndex-dealerName" v-model.trim="queryParam.dealerName" allowClear placeholder="请输入经销商名称"/>
                        </a-form-item>
                      </a-col>
                      <a-col :md="6" :sm="24">
                        <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="settingsIndex-refresh">查询</a-button>
                        <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="settingsIndex-reset">重置</a-button>
                      </a-col>
                    </a-row>
                  </a-form>
                  <!-- 操作按钮 -->
                  <div class="areaSet-btnGroup" style="margin-bottom:10px;">
                    <a-button type="primary" id="settingsIndex-addArea" class="button-info" @click="openAreaModal">选择区域</a-button>
                    <a-button type="primary" id="settingsIndex-addDealer" class="button-error" @click="openDealerModal">选择经销商</a-button>
                  </div>
                </div>
                <a-spin :spinning="spinning" tip="Loading...">
                  <!-- 列表 -->
                  <s-table
                    class="sTable fixPagination"
                    ref="table"
                    size="small"
                    :rowKey="(record) => record.id"
                    :columns="columns"
                    :data="loadData"
                    :defaultLoadData="false"
                    :style="{ height: tableHeight+70+'px' }"
                    :scroll="{ y: tableHeight }"
                    bordered>
                    <!-- 操作 -->
                    <template slot="action" slot-scope="text, record">
                      <a-button
                        size="small"
                        type="link"
                        class="button-error"
                        :id="'settingsIndex-del-btn'+record.id"
                        @click="handleDel(record)">删除</a-button>
                    </template>
                  </s-table>
                </a-spin>
              </div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="设置管辖品类" force-render v-if="infoObj.allProductFlag&&infoObj.allProductFlag!=1">
              <categorySet ref="setCategory" :bizUserSn="infoObj.bizUserSn"></categorySet>
            </a-tab-pane>
            <a-tab-pane key="3" tab="设置供应商" force-render v-if="infoObj.allSupplierFlag&&infoObj.allSupplierFlag!=1">
              <supplierSet ref="setSupplier" :bizUserSn="infoObj.bizUserSn"></supplierSet>
            </a-tab-pane>
          </a-tabs>
        </div>
      </a-card>
      <!-- 选择区域 -->
      <chooseAreaModal
        ref="partQuery"
        :showModal="openChooseArea"
        :chooseData="newChooseData"
        @ok="handleArea"
        @close="openChooseArea=false">
      </chooseAreaModal>
      <!-- 选择经销商 -->
      <a-drawer
        title="选择经销商"
        width="80%"
        :zIndex="100"
        :visible="openChooseDealer"
        :get-container="false"
        :wrap-style="{ position: 'absolute' }"
        @close="openChooseDealer = false">
        <div class="dealerModalCon">
          <chooseDealer ref="dealerChoose" @plAdd="handleAddDealer"></chooseDealer>
        </div>
      </a-drawer>
    </a-spin>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable } from '@/components'
import categorySet from './categorySet'
import supplierSet from './supplierSet'
import chooseAreaModal from './chooseAreaModal'
import chooseDealer from './chooseDealer.vue'
import subarea from '@/views/common/subarea.js'
// 接口
import { queryDealerScopePage, bizuserScopeDelete, findById, queryAreaScope, queryDealerScope, saveAreaScope, saveDealerScope } from '@/api/bizuser'
export default {
  name: 'SettingsIndex',
  mixins: [commonMixin],
  components: { STable, categorySet, chooseAreaModal, chooseDealer, subarea, supplierSet },
  data () {
    return {
      spinning: false,
      tableHeight: 0, // 表格高度
      disabled: false, //  查询、重置按钮是否可操作
      openChooseArea: false, // 打开选择区域弹窗
      openChooseDealer: false, // 打开选择经销商弹窗
      // 查询参数
      queryParam: {
        hasDetail: 0,
        bizType: undefined, // 区域分区区别
        bizSn: undefined, // 当前行sn
        dealerName: ''// 经销商
      },
      activeKeyVal: '1', // 选项卡值  1设置管辖区域 2设置管辖品类 3设置供应商
      infoObj: {}, // 基本信息数据
      newChooseData: {// 区域分区回显
        checked: [],
        halfChecked: []
      },
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '添加时间', dataIndex: 'createDate', width: '16%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '区域', dataIndex: 'subareaName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '分区', dataIndex: 'subareaAreaName', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '经销商', dataIndex: 'dealerName', width: '16%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: '8%', align: 'center' }
      ],
      chooseInfo: [], // 回显选中经销商信息
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        this.queryParam.userSn = this.$route.query.sn
        // 获取列表数据  有分页
        return queryDealerScopePage(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 计算列表序号
            const no = (data.pageNo - 1) * data.pageSize
            this.total = data.count || 0
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
            }
          }
          this.disabled = false
          this.spinning = false
          return data
        })
      }
    }
  },
  methods: {
    // 获取用户基本信息
    getBaseInfo () {
      const _this = this
      findById({ id: _this.$route.query.id }).then(res => {
        if (res.status == 200) {
          _this.infoObj = res.data
          if (res.data.allDealerFlag != 1) {
            _this.activeKeyVal = '1'
            _this.$nextTick(() => {
              _this.$refs.table.refresh()
            })
          } else if (res.data.allDealerFlag == 1 && res.data.allProductFlag != 1) {
            _this.activeKeyVal = '2'
            _this.$nextTick(() => {
              this.$refs.setCategory.pageInit()
            })
          } else if (res.data.allDealerFlag == 1 && res.data.allProductFlag == 1 && res.data.allSupplierFlag != 1) {
            _this.activeKeyVal = '3'
            _this.$nextTick(() => {
              this.$refs.setSupplier.pageInit()
            })
          }
        }
      })
    },
    // 选择区域>分区
    handleArea (con) {
      const chooseData = con.checked
      const newData = []
      chooseData.forEach(item => {
        const obj = {}
        obj.userSn = this.$route.query.sn
        obj.bizUserSn = this.infoObj.bizUserSn
        if (item.indexOf('_') != -1) { // 分区获取数据带_    区域不带下划线
          obj.bizType = 'subarea_area'
          obj.bizSn = item.replace('_', '')
          newData.push(obj)
        } else {
          obj.bizType = 'subarea'
          obj.bizSn = item
          newData.push(obj)
        }
      })
      this.saveChooseArea(newData)
    },
    // 保存区域分区数据
    saveChooseArea (list) {
      const _this = this
      const newAjaxData = {}
      newAjaxData.userSn = _this.$route.query.sn
      newAjaxData.bizUserScopeList = list
      saveAreaScope(newAjaxData).then(res => {
        if (res.status == 200) {
          _this.openChooseArea = false
          _this.resetSearchForm()
        }
      })
    },
    // tabs 选择
    handleTabs (val) {
      this.activeKeyVal = val
      if (val == 2) {
        this.$refs.setCategory.pageInit()
      } else if (val == 3) {
        this.$refs.setSupplier.pageInit()
      }
    },
    // 所在区域分区查询
    subareaChange (val) {
      if (val.length == 1) {
        this.queryParam.bizSn = val[0]
        this.queryParam.bizType = 'subarea'
      } else if (val.length == 2) {
        this.queryParam.bizSn = val[1]
        this.queryParam.bizType = 'subarea_area'
      } else {
        this.queryParam.bizSn = undefined
        this.queryParam.bizType = undefined
      }
    },
    // 重置
    resetSearchForm () {
      this.queryParam = {
        bizSn: undefined,
        bizType: undefined,
        dealerName: '',
        hasDetail: 0
      }
      if (this.infoObj && this.infoObj.allDealerFlag != 1) {
        this.$refs.subarea.clearData()
        this.$refs.table.refresh(true)
      }
    },
    // 选择区域
    async openAreaModal () {
      const _this = this
      const checkedArr = []
      const dataList = await queryAreaScope({ userSn: this.$route.query.sn, hasDetail: 0 })
      if (dataList.data && dataList.data.length > 0) {
        dataList.data.forEach(item => {
          if (item.bizType == 'subarea_area') {
            item.bizSn = item.bizSn + '_'
          }
          checkedArr.push(item.bizSn)
        })
        const newCheckedArr = [...new Set(checkedArr)]
        console.log('end choose:', newCheckedArr)
        this.newChooseData.checked = newCheckedArr
      } else {
        this.newChooseData.checked = []
      }
      this.$refs.partQuery.pageInit()
      _this.$nextTick(() => {
        _this.openChooseArea = true
      })
    },
    // 打开经销商弹窗
    async openDealerModal (params = {}) {
      const _this = this
      const arr = []
      const dataList = await queryDealerScope({ userSn: this.$route.query.sn, hasDetail: 0 })
      if (dataList.data && dataList.data.length > 0) {
        dataList.data.forEach(con => {
          arr.push(con.bizSn)
        })
        _this.chooseInfo = [...new Set(arr)]
      } else {
        _this.chooseInfo = []
      }
      const dataInfo = {
        list: _this.chooseInfo,
        sn: _this.$route.query.sn
      }
      _this.openChooseDealer = true
      if (_this.openChooseDealer) {
        _this.$refs.dealerChoose.pageInit(dataInfo)
      }
    },
    // 经销商
    handleAddDealer (list) {
      const newData = []
      list.forEach(con => {
        const obj = {}
        obj.userSn = this.$route.query.sn
        obj.bizUserSn = this.infoObj.bizUserSn
        obj.bizType = 'dealer'
        obj.bizSn = con
        newData.push(obj)
      })
      this.saveChooseDealer(newData)
    },
    // 保存所选区域或经销商
    saveChooseDealer (list) {
      const _this = this
      const ajaxData = {}
      ajaxData.userSn = _this.$route.query.sn
      ajaxData.bizUserScopeList = list
      saveDealerScope(ajaxData).then(res => {
        if (res.status == 200) {
          _this.openChooseDealer = false
          _this.resetSearchForm()
        }
      })
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '确认要删除吗？删除后当前用户权限以最新权限为准',
        centered: true,
        onOk () {
          bizuserScopeDelete({ id: row.bizUserScopeSn }).then(res => {
            if (res.status == 200) {
              _this.resetSearchForm()
            }
          })
        }
      })
    },
    //  返回
    handleBack () {
      this.$router.push({ name: 'businessOwnerSettings' })
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
      _this.getBaseInfo()
    },
    // 计算列表高度
    setTableH () {
      const headHeight = this.$refs.headerBar.offsetHeight
      this.tableHeight = window.innerHeight - headHeight - 340
    }
  },
  watch: {
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  activated () {
    this.pageInit()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less" scoped>
  .categorySet-wrap{
    .table-operator{
    text-align:right;
    }
  }
</style>
