<template>
  <div>
    <Row class="search-row">
      <i-col span="24"
             class="search-col">
        <Row class="row-style">
          <i-input placeholder="请输入推广员姓名或手机号"
                   class="search-select"
                   v-model="searchShop" />
          <span class="search-span">选择日期</span>
          <DatePicker :value="selectDate"
                      type="daterange"
                      split-panels
                      placeholder="请选择日期"
                      @on-change="onChangeDateLister"
                      class="date-picker"></DatePicker>
          <span class="search-span">零售公司</span>
          <Select v-model="companyId"
                  filterable
                  class="search-select"
                  @on-change="companySelect">
            <Option v-for="(item,index) in companyList"
                    :value="item.id"
                    :key="index + item.id">{{ item.name }}</Option>
          </Select>
          <span class="search-span">店铺</span>
          <Select v-model="selectedStore"
                  filterable
                  class="search-select">
            <Option v-for="(item,index) in shopList"
                    :value="item.id"
                    :key="index + item.id">{{ item.name }}</Option>
          </Select>
          <Button type="primary"
                  @click="searchCustomerDataBtnClick"
                  class="search-btn">查询</Button>

        </Row>
      </i-col>
    </Row>
    <Table ref="table"
           :loading="loading"
           :columns="columns1"
           :data="data1"
           class="table-store"
           size="small"
           @on-row-dblclick="onDblClickRowLister">
      <template slot="action"
                slot-scope="{row}">
        <i-col span="12">
          <Button type="success"
                  class="router-btn"
                  @click="() => {show(row)}">升级</Button>
        </i-col>
        <i-col span="12">
          <Button type="text"
                  class="router-btn"
                  style="color:2DBCF0!important"
                  @click="() => {doShow(true,row)}">查看上下级</Button>
        </i-col>
      </template>
    </Table>

    <!-- 升级 -->
    <Modal v-model="isShow"
           :title="showStoreName"
           :footer-hide="true"
           width="600"
           class-name="vertical-center-modal"
           @on-ok="ok">
      <div slot="header">
        <p style="text-align: center;">确认升级</p>
      </div>
      <div style="text-align:center;min-height:100px">
        <span style="line-height:100px">{{upgradeStr}}</span>
      </div>
      <div style="margin-top:20px;text-align: center;">
        <Button @click="cancel(rowData)">取消升级</Button>
        <Button style="margin-left:20px"
                type="primary"
                @click="confirm(rowData)">确定升级</Button>
      </div>
    </Modal>
    <recruitTable ref="recruitTable"
                  @doShow="doShow"
                  :show="showrecruit"
                  :schedule="recruitSchedule">
    </recruitTable>
    <Page :total="total"
          :current="pageNum"
          :page-size="pageSize"
          show-elevator
          show-total
          placement="top"
          @on-change="handlePage"
          class-name="ks-page"></Page>
  </div>
</template>

<script>
import recruitTable from "./recruitTable";
import zeroExtend from "../../services/customer/zeroExtend";
import staff from "../../services/staff/staff";
import { formatDate } from "../../utils/Common";
import bulletinService from '../../services/recruit/Bulletin'
export default {
  name: "",
  components: {
    recruitTable,
  },
  data () {
    return {
      tabIndex: 0,
      userId: JSON.parse(sessionStorage.getItem("loginInfo")).userId,
      searchShop: null,
      date: "",
      companyId: null,
      isShow: false,
      showStoreName: '',
      showrecruit: false,
      recruitSchedule: {},
      rowData: {},
      upgradeStr: "",
      //零售公司list
      companyList: [],
      selectedStore: null,
      shopList: [],
      loading: false,
      //所有组织list
      organizationalList: [],
      total: 0,
      pageSize: 10,
      pageNum: 1,
      columns1: [
        {
          title: '序号',
          key: 'number',
          width: 60,
          render: (h, params) => {
            return h('span', params.index + (this.pageNum - 1) * this.pageSize + 1);
          }
        },
        {
          title: '推广员姓名',
          key: 'shopName',
          width: 120,
          render: (h, params) => {
            return h('span', params.row.promoterInfo.name);
          }
        },
        {
          title: '推广员手机号',
          key: 'shopPhone',
          width: 120,
          render: (h, params) => {
            return h('span', params.row.promoterInfo.phone);
          }
        },
        {
          title: '等级',
          width: 80,
          render: (h, params) => {
            let str = "";
            switch (params.row.level) {
              case 1:
                str = "一般推广员";
                break;
              case 2:
                str = "客户经理";
                break;
              case 3:
                str = "服务经理";
                break;
              default:
                str = "一般推广员";
            }
            return h('span', str);
          }
        },
        {
          title: '客户经理数',
          key: 'customerManagerCount',
          width: 120
        },
        {
          title: '推广员数',
          key: 'extensionCount',
          width: 120
        },
        {
          title: '客户数',
          key: 'customerCount',
          width: 80
        },
        {
          title: '业绩',
          key: 'achievement',
          width: 80
        },
        {
          title: '零售公司',
          key: 'companyName',
          width: 150,
          render: (h, params) => {
            return h('span', params.row.organizational.name);
          }
        },

        {
          title: '店铺',
          key: 'storeName',
          width: 160,
          render: (h, params) => {
            return h('span', params.row.store.name);
          }
        },
        {
          title: '店铺编号',
          key: 'storeNO',
          width: 80,
          render: (h, params) => {
            return h('span', params.row.store.code);
          }
        },
        {
          title: '发展人',
          key: 'fissionNum',
          width: 80,
          render: (h, params) => {
            return h('span', params.row.fissionUser.name);
          }
        },
        {
          title: '加入时间',
          key: 'submitDate',
          width: 120,
          render: (h, params) => {
            return h('span', formatDate(params.row.joinTime));
          }
        },
        {
          title: '操作',
          slot: 'operation',
          width: 250,
          render: (h, params) => {
            let that = this;
            return h('div', [
              h('span', {
                style: {
                  background: 'white',
                  border: '0',
                  color: '#3496EB',
                  marginRight: '15px',
                  cursor: 'pointer'
                },
                on: {
                  click: () => {
                    that.show(params.row)
                  }
                }
              }, '升级'),
              h('span', {
                style: {
                  background: 'white',
                  border: '0',
                  color: '#3496EB',
                  marginRight: '15px',
                  cursor: 'pointer'
                },
                on: {
                  click: () => {
                    that.doShow(true, params.row)
                  }
                }
              }, '查看上下级'),

            ])

          }
        }
      ],
      data1: [

      ],
      selectDate: [],
    }
  },
  mounted: function () {
    this.getSelectList();
    this.downShopData();
    this.getPromoterList();
  },
  methods: {
    onChangeDateLister (date) {
      console.log(date)
      this.selectDate = date;
    },
    /**基础数据：区域list、零售公司list、客户list*/
    getSelectList: function () {
      let that = this;
      let request = {
        userId: this.userId,
      };
      zeroExtend.getSelectListRequest(request, function (data) {
        if (data.data.code !== "0000") {
          that.$Message.error("系统异常");
        }
        data = data.data.results;
        if (data) {
          that.organizationalList = data;
          that.companyList = that.organizationalList.filter(item => item.level === 2);
        }
        //插入全部选项
        that.insertAllOption();
      });
    },
    //插入全部选项
    insertAllOption: function () {
      if (this.companyList.length === 0 || this.companyList[0].id !== 0) {
        this.companyList.splice(0, 0, { "id": 0, "name": "全部" });
      }
      if (this.shopList.length === 0 || this.shopList[0].id !== 0) {
        this.shopList.splice(0, 0, { "id": 0, "name": "全部" });
      }
    },
    //店铺
    downShopData: function (selected) {
      let that = this;
      let companyId = selected;
      if (!selected) {
        companyId = that.companyId;
      }
      let customerIds = [];
      this.customerList = [];
      if (companyId === 0) {
        //
      } else {
        this.customerList = this.organizationalList.filter(item => item.parentId === companyId && item.level === 3);
        this.insertAllOption();
      }
      customerIds = this.customerList.map(item => item.id);

      let request =
        { userId: that.userId, customerIds: JSON.stringify(customerIds) };
      staff.downShopData(request, function (data) {
        data = data.data.results;
        if (data) {
          that.shopList = [{ "id": 0, "name": "全部" }];
          for (let i = 0; i < data.length; i++) {
            let entity = data[i];
            if (entity) {
              that.shopList.push(entity);
            }
          }
        }
      })
    },
    //零售公司选择
    companySelect: function () {
      //加载店铺
      this.downShopData(this.companyId);
      this.selectedStore = 0;
    },
    downCompanyChange: function (formValidate) {
      this.downShopData(formValidate.departIds);
    },
    searchCustomerDataBtnClick: function () {
      this.pageNum = 1;
      this.getPromoterList();
    },
    // 双击row跳转详情页面
    onDblClickRowLister: function (row) {
      this.$router.push({ path: '/shop/increase/manager/staff', query: { storeId: row.id } });
    },
    //切页处理
    handlePage: function (value) {
      this.pageNum = value;
      this.getPromoterList();
    },
    getPromoterList () {
      let that = this;
      this.loading = true;
      let request = {
        pageNum: that.pageNum,
        storeId: that.selectedStore,
        companyId: that.companyId,
        store: that.searchShop,
        start: that.selectDate[0] === "" || that.selectDate.length == 0 ? null : that.selectDate[0],
        end: that.selectDate[1] === "" || that.selectDate.length == 0 ? null : that.selectDate[1],
      };
      bulletinService.promoterList(request, function (data) {
        that.loading = false;
        if (data.data.code == "0000") {
          that.data1 = [];
          let datas = data.data.results;
          //总页数
          if (datas.total == null) {
            that.total = 0;
          } else {
            that.total = datas.total;
          }
          if (datas.list == null) {
            datas.list = [];
          }
          that.data1 = datas.records;
        }
      }, function (error) {
        that.loading = false;
      });
    },
    onTabClick (e) {
      this.tabIndex = e;
      console.log('tabIndex', this.tabIndex);
    },
    ok () {
      this.isShow = false;
    },
    cancel () {
      this.isShow = false;
    },
    // 升级
    confirm (rData) {
      let request = {
        promoterId: rData.id
      }
      let that = this;
      bulletinService.promoterUpgrade(request, function (data) {
        that.loading = false;
        if (data.data.code == "0000") {
          that.$Message.info("升级成功");
          that.getPromoterList();
        } else {
          that.$Message.error("系统异常");
        }
      }, function (error) {
        that.loading = false;
      });
      this.isShow = false;
    },
    show (index) {
      if (index.level >= 3) {
        that.$Message.error(`${index.name}的等级已是最高`);
        return false;
      }
      this.isShow = true;
      this.rowData = index;
      let str = "";
      let next = "";
      switch (index.level) {
        case 1:
          str = "一般推广员";
          next = "客户经理";
          break;
        case 2:
          str = "客户经理";
          next = "服务经理";
          break;
        case 3:
          str = "服务经理";
          next = "服务经理";
          break;
        default:
          str = "一般推广员";
      }
      this.upgradeStr = `确认将${index.name}从${str}升级成${next}吗?`;
    },
    doShow (ishow, currData) {
      this.showrecruit = ishow;
      if (ishow) {
        this.recruitSchedule = currData;
      }
    },
  }
}
</script>

<style scoped>
.table-store {
  margin-top: 20px;
}
.search-btn {
  margin-left: 40px;
}
</style>
