<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <!-- el-col :span="4" :xs="24" >
        <div class="head-container">
        </div>
        <div class="head-container" style="overflow-x:scroll">
          <el-tree
            :props="defaultProps"
            ref="tree"
            :load="loadNode"
            :data="channelOptions"
            lazy
            @node-click="handleNodeClick"
          />
        </div>
      </el-col> -->
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="渠道名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入渠道名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="渠道级别" prop="level">
            <el-select
              v-model="queryParams.level"
              placeholder="选择渠道级别"
              clearable
              size="small"
              @change="handleQuery()"
              style="width: 200px;margin-right: 1px;">
              <el-option label="全部" value="" />
              <el-option label="1级渠道" value="1" />
              <el-option label="2级渠道" value="2" />
              <el-option label="3级渠道" value="3" />
              <el-option label="4级渠道" value="4" />
              <el-option label="5级渠道" value="5" />
              <el-option label="6级渠道" value="6" />
            </el-select>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
         <el-form-item label="地区">
           <el-select
             v-model="queryParams.provinceId"
             placeholder="选择省份"
             clearable
             size="small"
             @change="getCityList()"
             style="width: 120px;margin-right: 1px;">
             <el-option
               v-for="item in provinceList"
               :key="item.areaId"
               :label="item.areaName"
               :value="item.areaId"
             />
           </el-select>
           <el-select
             v-model="queryParams.cityId"
             placeholder="选择市"
             clearable
             size="small"
              @change="getAreaList()"
             style="width: 120px;margin-right: 1px;">
             <el-option
               v-for="item in cityList"
               :key="item.areaId"
               :label="item.areaName"
               :value="item.areaId"
             />
           </el-select>
           <el-select v-model="queryParams.areaId" placeholder="选择区" clearable size="small" style="width: 120px;margin-right: 1px;">
             <el-option
               v-for="item in areaList"
               :key="item.areaId"
               :label="item.areaName"
               :value="item.areaId"
             />
           </el-select>
         </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['business:channel:add']"
            >添加一级渠道</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="channelList" @sort-change="sortChannelId" >
          <el-table-column label="渠道编号" sortable="custom" prop="channelId" width="100px" />
          <el-table-column label="渠道名称" prop="name" show-overflow-tooltip  width="180px">
            <template slot-scope="scope">

              <el-button
                  v-if="scope.row.childCnt > 0"
                  size="mini"
                  type="text"
                  @click="handleView(scope.row)"
                >
                  <pre>{{scope.row.name}}</pre>
              </el-button>
              <span v-else><pre>{{scope.row.name}}</pre></span>
            </template>
          </el-table-column>
          <el-table-column label="手机号码" prop="mobile" show-overflow-tooltip  width="120px"/>
          <el-table-column label="佣金比例" prop="commRate" sortable="custom">
            <template slot-scope="scope">
              {{scope.row.commRate}}%
            </template>
          </el-table-column>
          <el-table-column label="渠道级别" prop="level">
            <template slot-scope="scope">
              {{scope.row.level}}级渠道
            </template>
          </el-table-column>
          <el-table-column label="门店数" sortable="custom" prop="siteCnt"  />
          <el-table-column label="用户数" sortable="custom" prop="userCnt"  />
          <el-table-column label="注册时间" prop="createdTime" min-width="150px">
            <template slot-scope="{ row }">
              {{ parseTime(row.createdTime) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" key="statusV">
           <template slot-scope="{ row, column }">
             <el-tag :type="JSON.parse(row.status).value == '1' ? 'success' : 'info'">{{ JSON.parse(row.status).desc }}</el-tag>
           </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope" v-if="scope.row.userId !== 1">
              <el-button
                size="mini"
                type="text"
                @click="handleDetail(scope.row)"
                v-hasPermi="['business:channel:query']"
              >查看</el-button>
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:channel:edit']"
              >编辑</el-button>
              <el-button
                  size="mini"
                  type="text"
                  @click="handleStatusChange(scope.row)"
                  v-hasPermi="['business:channel:edit']"
                >
                  <span v-if="getValue(scope.row.status) == 1" > 停用</span>
                  <span v-if="getValue(scope.row.status) == 2" > 启用</span>
                </el-button>
             <!-- <el-switch
               style="margin-left: 9px;"
               v-model="scope.row.statusV"
               active-value="1"
               inactive-value="2"
               v-hasPermi="['business:channel:edit']"
               @change="handleStatusChange(scope.row)"
             ></el-switch> -->

             <!-- <el-button
                size="mini"
                type="text"
                disabled
                icon="el-icon-plus"
                @click="handleAdd(scope.row)"
                v-hasPermi="['admin:channel:add']"
              >添加子渠道</el-button> -->
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="pageParams.pageNum"
          :limit.sync="pageParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 新建 -->
    <channel-create
      v-if="createShow"
      :dialog-visible="createShow"
      :edit-id="editId"
      @saveSuccess="submitSuccess"
      @close="hideDialog"
    />

    <!-- 详情 -->
    <channel-detail
      v-if="detailShow"
      :dialog-visible="detailShow"
      :edit-id="editId"
      @close="hideDialog"
    />

  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { treeChannel, listChannel, updateChannelStatus} from "@/api/admin/channel";
import { listAreaByPid} from "@/api/admin/area";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ChannelCreate from './components/Create'
import ChannelDetail from './components/Detail'
export default {
  name: "Channel",
  components: {
    Treeselect,
    ChannelCreate,
    ChannelDetail
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 创建编辑
      createShow: false,
      // 详情
      detailShow: false,
      provinceList:[],
      cityList:[],
      areaList:[],
      // 编辑项ID
      editId: null,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      channelList: [],
      channelOptions: [],
      channelName:"",
      // 状态数据字典
      statusOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 查询参数
      queryParams: {
        name: "",
        mobile: "",
        provinceId:"",
        cityId:"",
        areaId:""
      },
      pageParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'channelId',
        isAsc: 'desc',

      }
    };
  },
  watch: {
    // 根据渠道名称筛选渠道树
    //channelName(val) {
      // this.$refs.tree.filter(val);
    //}
  },
  mounted() {
     this.getProvinceList()

  },
  created() {
     this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listChannel('pageNum='+this.pageParams.pageNum + '&pageSize='+this.pageParams.pageSize+'&orderByColumn='+ this.pageParams.orderByColumn +'&isAsc='+ this.pageParams.isAsc +'&', this.queryParams).then(response => {
          this.channelList = response.rows;
          this.channelList.forEach(item => {
              item.statusV = JSON.parse(item.status).value+""
          })
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.parentId = data.channelId;
      this.getList();
    },
    // 懒加载节点
    loadNode(node, resolve) {
      if(node.level === 0){
       treeChannel({}).then(response => {
          return resolve(response.data);
       });
      }else{
        var params = {
          parentId:node.data.channelId
        }
        treeChannel(params).then(response => {
           return resolve(response.data);
        });
      }
    },

    //切换排序
    sortChannelId(row){
      if (row){
        let prop =  row.prop == 'commRate' ? ('t1.'+ row.prop) : row.prop;
        this.pageParams.orderByColumn = prop
        this.pageParams.isAsc = row.order=='ascending'?"asc":"desc";
        this.getList()
      }

    },

    refreshChannelTree(){
      treeChannel({}).then(response => {
         this.channelOptions = response.data
      });
    },

    // 省
    getProvinceList(){
      this.cityList = []
      this.areaList = []
      this.queryParams.cityId = ""
      this.queryParams.areaId = ""
      listAreaByPid(0).then(response => {
        // console.log("getProvinceList"+JSON.stringify(response))
         this.provinceList = response || [];
      });
    },

    getCityList(){
      this.cityList = []
      this.areaList = []
      this.queryParams.cityId = ""
      this.queryParams.areaId = ""
      var provinceId = this.queryParams.provinceId
      listAreaByPid(provinceId).then(response => {
        // console.log("getCityList"+JSON.stringify(response))
         this.cityList = response || [];
      });
    },

    getAreaList(){
      var cityId = this.queryParams.cityId
      listAreaByPid(cityId).then(response => {
        // console.log("getAreaList"+JSON.stringify(response))
         this.areaList = response || [];
      });
    },

    // 状态修改
    handleStatusChange(row) {
      var newStatus = this.getValue(row.status) == 2?1:2
      let text = this.getValue(row.status) == 2 ? "启用" : "停用";
      this.$confirm('确认要"' + text + '""' + row.name + '"渠道吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          var params={
            channelId:row.channelId,
            status: newStatus
          }
          return updateChannelStatus(params);
        }).then(() => {
          this.msgSuccess(text + "成功");
          this.getList();
        }).catch(function() {
          // row.status = row.status === "0" ? "1" : "0";
        });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.pageParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams= {
         name: "",
         mobile: "",
         provinceId:"",
         cityId:"",
         areaId:""
      },
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleDetail(row){
      this.detailShow = true
      this.editId = row.channelId
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.createShow = true
      this.editId = null
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.createShow = true
      this.editId = row.channelId
    },
    // 保存后的操作
    submitSuccess(){
      this.getList();
      this.refreshChannelTree();
    },
    /**关闭弹窗*/
    hideDialog(){
      this.createShow = false
      this.detailShow = false
    },

    getDesc(val) {
      // console.log("val == "+val);
      const dataObj = JSON.parse(val);
      return (dataObj && dataObj.desc) || "";
    },

    getValue(val) {
      // console.log("val == "+val);
      const dataObj = JSON.parse(val);
      return (dataObj && dataObj.value) || "";
    },

    handleView(row) {
      // this.createShow = true
      let parentId = row.channelId
      let title = row.name
      // this.action = 'view'
      const path = "/channel/channel/childs"
      // const routerName = "BillItems"
      this.$router.push({
        path: path ,
        query: {
          parentId: parentId,
          title: title
        },
        meta:{
          title:"777777777777777777"
        }
      });
    },
  }
};
</script>
<style lang="sass" scoped>

</style>
