<template>
  <div class="app-container">
    <div v-show="viewState ==1">
      <button-bar view-title="经销商管理" ref="btnbar" :btndisabled="btndisabled" @btnhandle="btnHandle"/>
      <div class="main-content">
        <div class="searchcon">
          <el-button size="small" class="searchbtn" @click="clicksearchShow">{{ searchxianshitit }}</el-button>
          <div v-show="isSearchShow" class="search">
            <el-form ref="listQueryform" :inline="true" :model="listQuery" label-width="130px" class="tab-header">
              <el-form-item label="经销商名称">
                <el-input v-model="listQuery.params.disName" placeholder="请输入经销商名称" clearable
                          class="filter-item"/>
              </el-form-item>
              <el-form-item label="统一社会信用代码">
                <el-input v-model="listQuery.params.registNum" placeholder="请输入统一社会信用代码" clearable class="filter-item"/>
              </el-form-item>
              <el-form-item label="实际控制人姓名">
                <el-input v-model="listQuery.params.legalName" placeholder="请输入实际控制人姓名" clearable
                          class="filter-item"/>
              </el-form-item>
              <el-form-item label="级别">
                <el-select v-model="listQuery.params.disLevelKey" class="filter-item" clearable placeholder="请选择状态">
                  <el-option v-for="item in disLevel_list" :key="item.dictKey" :label="item.dictValue"
                             :value="item.dictKey"/>
                </el-select>
              </el-form-item>
              <el-form-item label="是否担保">
                <el-select v-model="listQuery.params.isGuarantee" class="filter-item" clearable placeholder="请选择是否担保">
                  <el-option v-for="item in options" :key="item.key" :label="item.label" :value="item.key"/>
                </el-select>
              </el-form-item>
              <el-form-item label="所属经销商">
                <el-select v-model="listQuery.params.pdistributorSid" class="addinputw" placeholder="请选择所属经销商"
                           clearable>
                  <el-option v-for="(item,index) in pDistributorSid_list" :key="item.sid" :label="item.disName"
                             :value="item.sid"/>
                </el-select>
              </el-form-item>
              <el-form-item label="成立日期">
                <el-date-picker
                  v-model="listQuery.params.setUpStartTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
                <span style="padding: 0 8px">至</span>
                <el-date-picker
                  v-model="listQuery.params.setUpEndTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-form>
            <div class="btn" style="text-align: center;">
              <el-button type="primary" @click="handleFilter">查询</el-button>
              <el-button type="primary" @click="handleReset">重置</el-button>
            </div>
          </div>
        </div>
        <div class="listtop">
          <div class="tit">经销商信息列表</div>
          <div class="rel_css">
            <span style="font-size: 15px">关联状态：</span>
            <el-select v-model="listQuery.params.relationState" class="filter-item rel_btn" clearable placeholder="请选择关联关系"
                       @change="relationStateChange">
              <el-option v-for="item in optionsRel" :key="item.key" :label="item.label" :value="item.key"/>
            </el-select>
          </div>
          <pageye v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current"
                  :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
        <div>
          <el-table :key="tableKey" v-loading="listLoading" :data="list" border style="width: 100%;"
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center" width="50"/>
            <el-table-column label="序号" fixed type="index" width="80" :index="indexMethod" align="center"/>
            <el-table-column label="操作" fixed align="center" width="170px">
              <template slot-scope="{row}">
                <el-button size="mini" type="primary" @click="handleEdit(row)">办理</el-button>
                <el-button size="mini" type="primary" @click="handleCheck(row)">查看</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="state" label="状态" width="120" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.state }}</span>
              </template>
            </el-table-column>
            <el-table-column label="所属经销商" width="180" align="center"> <!-- ? -->
              <template slot-scope="scope">
                <span>{{ scope.row.pdistributorName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="经销商名称" width="180" header-align="center" align="left">
              <template slot-scope="scope">
                <span class="bluezi" @click="handleCheck(scope.row)">{{ scope.row.disName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="统一社会信用代码" width="190" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.registNum }}</span>
              </template>
            </el-table-column>
            <el-table-column label="注册地址" width="220" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.registDetailAddress }}</span>
              </template>
            </el-table-column>
            <el-table-column label="联系电话" width="120" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.invoPhone }}</span>
              </template>
            </el-table-column>
            <el-table-column label="开户行" width="110" align="center"> <!-- ? -->
              <template slot-scope="scope">
                <span>{{ scope.row.invoBank }}</span>
              </template>
            </el-table-column>
            <el-table-column label="银行账号" width="190" align="center"> <!-- ? -->
              <template slot-scope="scope">
                <span>{{ scope.row.invoBankNum }}</span>
              </template>
            </el-table-column>
            <el-table-column label="成立日期" width="120" align="center"> <!-- ? -->
              <template slot-scope="scope">
                <span>{{ scope.row.setUpTime }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否担保" width="120" align="center"> <!-- ? -->
              <template slot-scope="scope">
                <span>{{ scope.row.isGuarantee }}</span>
              </template>
            </el-table-column>
            <el-table-column label="本年销售台数" width="160" align="center"> <!-- ? -->
              <template slot-scope="scope">
                <span>{{ scope.row.curYearSaleNum }}</span>
              </template>
            </el-table-column>
            <el-table-column label="累计销售台数" width="160" align="center"> <!-- ? -->
              <template slot-scope="scope">
                <span>{{ scope.row.cumSaleNum }}</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pages">
          <div class="tit"/>
          <!-- 翻页 -->
          <pagination v-show="list.length > 0" :total="listQuery.total" :page.sync="listQuery.current"
                      :limit.sync="listQuery.size" class="pagination" @pagination="getList"/>
        </div>
      </div>
    </div>
    <guakaogongsiAdd v-show="viewState == 2 || viewState ==3" ref="divAdd" @doback="resetState" @reloadlist="getList"/>
    <guakaogongsiInfo v-show="viewState == 4" ref="divInfo" @doback="resetState"/>
  </div>
</template>

<script>
import {deleteBySids, getOneLevelList, pagerList, typeValues} from '@/api/jichuxinxi/baseaffiliatcompany'
import {getUseOrgByUserSid} from '@/api/jichuxinxi/brandManagement'
import {setuser} from '@/utils/baocun'
import Pagination from '@/components/pagination'
import pageye from '@/components/pagination/pageye'
import guakaogongsiAdd from './guakaogongsiAdd.vue'
import guakaogongsiInfo from './guakaogongsiInfo.vue'
import ButtonBar from '@/components/ButtonBar/index.vue'

export default {
  name: 'guakaogongsiguanli',
  components: {
    Pagination,
    pageye,
    guakaogongsiAdd,
    guakaogongsiInfo,
    ButtonBar
  },
  data() {
    return {
      isSearchShow: false,
      searchxianshitit: '显示查询条件',
      viewState: 1,
      // --按钮菜单-------
      btndisabled: false,
      btnList: [
        {
          type: 'primary',
          size: 'small',
          icon: 'plus',
          btnKey: 'toAdd',
          btnLabel: '新增'
        },
        {
          type: 'danger',
          size: 'small',
          icon: 'del',
          btnKey: 'doDel',
          btnLabel: '删除'
        },
        {
          type: 'success',
          size: 'small',
          icon: 'export',
          btnKey: 'build',
          btnLabel: '导出'
        },
        {
          type: 'info',
          size: 'small',
          icon: 'cross',
          btnKey: 'doClose',
          btnLabel: '关闭'
        }
      ],
      // 查询 -----------
      tableKey: 0,
      sids: [],
      list: [],
      FormLoading: false,
      listLoading: false,
      pDistributorSid_list: [],
      // 是否是担保人
      options: [{
        key: 1,
        label: '是'
      }, {
        key: 0,
        label: '否'
      }],
      // 是否关联
      optionsRel: [{
        key: 1,
        label: '已关联'
      }, {
        key: 0,
        label: '未关联'
      }],
      listQuery: {
        params: {
          createOrg: '',
          disName: '',	//经销商名称
          isGuarantee: '',	//是否担保 0是/1否
          legalName: '',	//实际控制人姓名
          registNum: '',	//统一社会信用代码
          disLevel: '', // 级别
          pdistributorSid: '',
          setUpEndTime: '',	//成立结束时间
          setUpStartTime: ''	// 成立开始时间
        },
        total: 0,
        current: 1,
        size: 10
      },
      temp: {}, // 添加和修改
      sdies: '',
      dialogFormVisible: false, // 添加修改对话框状态
      dialogFormShowVisible: false, // 查看对话框默认关闭状态
      dialogStatus: '', // 对话框状态
      disLevel_list: [] // 级别
    }
  },
  mounted() {
    this.$refs["btnbar"].setButtonList(this.btnList)
  },
  created() {
    // 初始化变量
    this.init()
    // 加载列表
    this.getListOrgAll()
  },
  methods: {
    // 搜索条件效果
    clicksearchShow() {
      this.isSearchShow = !this.isSearchShow
      if (this.isSearchShow) {
        this.searchxianshitit = '隐藏查询条件'
      } else {
        this.searchxianshitit = '显示查询条件'
      }
    },
    init() {
      this.getType()
      // 根据当前用户. 加载当前页面的按钮权限
      // findButtonByUserId(this.$route.path).then(response => {
      //   if (
      //     response.code === 20000 &&
      //   response.data &&
      //   response.data.length > 0
      //   ) {
      //     this.menuState = ConvertMenuState(response.data) // 处理各按钮显示状态
      //   }
      // })
    },
    btnHandle(btnKey) {
      console.log('XXXXXXXXXXXXXXX    ' + btnKey)
      switch (btnKey) {
        case 'toAdd':
          this.toAdd()
          break
        case 'doDel':
          this.doDel()
          break
        case 'doExport':
          this.doExport()
          break
        case 'doClose':
          this.doClose()
          break
        default:
          break
      }
    },
    // 序号
    indexMethod(index) {
      var pagestart = (this.listQuery.current - 1) * this.listQuery.size
      var pageindex = index + 1 + pagestart
      return pageindex
    },
    getListOrgAll(state) {
      const userSid = window.sessionStorage.getItem('userSid')
      getUseOrgByUserSid({userSid: userSid}).then((res) => {
        if (res.success) {
          console.log('获取当前使用人分公司', res.data)
          this.listQuery.params.relationState = state
          this.listQuery.params.createOrg = res.data.sid
          this.getList()
        }
      })
    },
    // 获取数据字典
    getType() {
      typeValues({type: 'disLevel'}).then((res) => {
        if (res.code === '200') {
          this.disLevel_list = res.data
        }
      })
    },
    getLevelList(){
      getOneLevelList({sid:''}).then((res) => {
        if (res.code === '200') {
          this.pDistributorSid_list = res.data
        }
      })
    },
    relationStateChange(val){
      this.getListOrgAll(val)
    },
    // 查询列表信息
    getList() {
      this.listLoading = true
      pagerList(this.listQuery).then((response) => {
        console.log('列表查询结果1：', response)
        console.log('列表查询结果：' + JSON.stringify(response))
        this.listLoading = false
        if (
          response.code === '200' &&
          response.data &&
          response.data.total > 0
        ) {
          this.list = response.data.records
          for (var i = 0; i < this.list.length; i++) {
            if (this.list[i].isGuarantee == '1') {
              this.list[i].isGuarantee = '是'
            } else if (this.list[i].isGuarantee == '0') {
              this.list[i].isGuarantee = '否'
            }
          }
          this.listQuery.total = response.data.total
        } else {
          this.list = []
          this.listQuery.total = 0
        }
      })
      this.getLevelList()
    },
    // 查询按钮
    handleFilter() {
      this.listQuery.current = 1
      this.getListOrgAll()

    },
    handleReset() {
      this.listQuery = {
        params: {
          disName: '',	//经销商名称
          isGuarantee: '',	//是否担保 0是/1否
          legalName: '',	//实际控制人姓名
          registNum: '',	//统一社会信用代码
          disLevel: '', // 级别
          pdistributorSid: '',
          setUpEndTime: '',	//成立结束时间
          setUpStartTime: ''	// 成立开始时间
        },
        total: 0,
        current: 1,
        size: 10
      }
      this.getListOrgAll()
    },
    handleSelectionChange(row) {
      const aa = []
      row.forEach((element) => {
        aa.push(element.sid)
        setuser(this.sids)
      })
      this.sids = aa
      this.sdies = this.sids.join()
      console.log('this.sids000000', this.sdies)
    },
    // 打开添加
    toAdd() {
      // this.$router.push({
      //   path: '/guakaogongsi/guakaogongsiAdd/0'
      // })
      this.viewState = 2
      this.$refs['divAdd'].showAdd()
    },
    // 打开修改
    toEdit() {
      if (this.sids.length === 1) {
        this.dialogStatus = 'update'
        this.viewState = 3
        this.$refs['divAdd'].showEdit(this.sids)
      } else if (this.sids.length > 1) {
        this.$notify({
          title: '提示',
          message: '不能选中多个经销商信息修改!!',
          type: 'info',
          duration: 2000
        })
      } else {
        this.$notify({
          title: '提示',
          message: '没有选择经销商信息!!',
          type: 'error',
          duration: 2000
        })
        return
      }
    },
    // 打开任务
    handleRenwu() {
      this.$router.push({
        path: '/guakaogongsi/renwu'
      })
    },
    handleEdit(row) {
      this.dialogStatus = 'update'
      // if (row.isRelation == '0'){
      this.viewState = 3
      this.$refs['divAdd'].showEdit(row.sid)
      // } else {
      //   this.$message({
      //     showClose: true,
      //     message: '所选经销商已关联二级经销商，无法修改！',
      //     type: 'error'
      //   });
      // }
    },
    // 打开查看
    handleCheck(scope) {
      this.viewState = 4
      this.$refs['divInfo'].showInfo(scope.sid)
    },
    // 根据本行ID删除数据
    doDel() {
      if (this.sdies.length > 0) {
        const _this = this
        const tip = '请确认是否删除所选 ' + this.sids.length + ' 条记录?'
        this.$confirm(tip, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            const loading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            deleteBySids({sids:this.sdies})
              .then(resp => {
                if (resp.success && resp.code == '200') {
                  loading.close()
                  _this.$message({type: 'success', message: resp.msg, showClose: true})
                  _this.getListOrgAll()
                } else {
                  loading.close()
                  // _this.$message({ type: 'error', message: resp.msg, showClose: true })
                }
              })
              .catch(e => {
                loading.close()
              })
          })
          .catch(() => {
          })
      } else {
        this.$notify({
          title: '提示',
          message: '没有选择经销商信息!!',
          type: 'error',
          duration: 2000
        })
        return
      }
    },
    resetState() {
      this.viewState = 1
    },
    // 导出
    doExport(row) {
      this.$confirm('确定要导出数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
    },
    // 发起审核流程
    handleShenHeLiuCheng(row) {
      this.$confirm('确定要发起审核流程吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      // .then(() => {
      //   const tempData = Object.assign({}, row) // copy obj
      //   // console.log('测试删除ID' + JSON.stringify(tempData.id))
      //   delServiceType(tempData.id).then(response => {
      //     if (response.code === 20000) {
      //       // console.log('测试删除' + JSON.stringify(response))
      //       this.$notify({
      //         title: '提示',
      //         message: '成功',
      //         type: 'success',
      //         duration: 2000
      //       })
      //       this.getList()
      //     } else {
      //       this.$notify({
      //         title: '失败',
      //         message: response.msg,
      //         type: 'error'
      //       })
      //     }
      //   })
      // })
      // .catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消'
      //   })
      // })
    },
    doClose() {
      this.$store.dispatch('tagsView/delView', this.$route);
      this.$router.go(-1)
    }

  },
}
</script>
<style scoped>
/deep/ .el-collapse {
  border-top: 0px solid #e6ebf5;
  border-bottom: 0px solid #e6ebf5;
}

/deep/ .el-collapse-item__content {
  margin: 0;
  padding: 0;
}

/deep/ .el-collapse-item__wrap {
  border-bottom: 0px solid #ebeef5;
}

/deep/ .el-collapse-item__header {
  border-bottom: 0px solid #e6ebf5;
}

.searchli {
  padding: 5px 100px;
}

.btn {
  padding: 15px 0 15px 0;
  border: 1px solid #e0e3eb;
}

.tab-header {
  background-color: #edf1f7;
  padding: 8px 20px;
  margin-bottom: 0 !important;
}
.listtop{
  position: relative;
}
.rel_css {
  position: absolute;
  right: 150px;
}
.rel_btn{
  height: 28px;
}
.rel_btn /deep/ .el-input__inner{
  height: 28px;
}
.rel_btn /deep/ .el-input__icon{
  line-height: 28px;
}
</style>
