<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="parentName">
           <el-input
             v-model="queryParams.parentName"
             placeholder="请输入上级渠道名称"
             clearable
             size="small"
             style="width: 240px"
             @keyup.enter.native="handleQuery"
           />
          </el-form-item>
          <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>
            <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)"
                >
                  {{scope.row.name}}
              </el-button>
              <span v-else>{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号码" prop="mobile" show-overflow-tooltip  width="120px"/>
          <el-table-column label="佣金比例" sortable="custom" prop="commRate">
            <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="状态" 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-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"
                 @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-button size="mini" type="text" v-if="scope.row.isTransform" @click="changeUpdate(scope.row)" v-hasPermi="['business:channel:edit']">转换角色</el-button>
             <!-- <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"
    />
    <!-- 渠道转换门店 -->
    <change-store v-if="changeShow" :dialog-visible="changeShow" @saveSuccess="submitSuccess" :edit-id="editId" @close="hideDialog" />
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { listChannel, updateChannelStatus} from "@/api/admin/channel";
import { listAreaByPid} from "@/api/admin/area";
import ChannelCreate from './components/Create'
import ChannelDetail from './components/Detail'
import ChangeStore from './components/ChangeStore.vue'
export default {
  name: "ChannelIndex",
  components: {
    ChannelCreate,
    ChannelDetail,
    ChangeStore
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 创建编辑
      createShow: false,
      // 详情
      detailShow: false,
      changeShow: false,
      provinceList:[],
      cityList:[],
      areaList:[],
      // 编辑项ID
      editId: null,
      parentId: null,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      channelList: [],
      channelOptions: [],
      channelName:"",
      title:"",
      // 状态数据字典
      statusOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 查询参数
      queryParams: {
        name: "",
        mobile: "",
        parentName: ""
      },
      pageParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'channelId',
        isAsc: 'desc',
      }
    };
  },
  watch: {
    // 根据渠道名称筛选渠道树
  },
  mounted() {
    // this.getProvinceList()
  },
  created() {
    let parentId = this.$route.query.parentId
    let title= this.$route.query.title
    this.title = title
    this.parentId = parentId
    this.queryParams.parentId = parentId
    this.queryParams.parentName = title
    // console.log("parentId == "+parentId+  "title == "+title)
   // this.$route.meta.title = title + " - 子渠道管理"
    if(parentId){
        this.initList();
    }
  },
  methods: {

    initList(){
      this.pageParams.pageNum = 1
      this.getList();
    },

    /** 查询用户列表 */
    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;
        }
      );
    },

    //切换排序
    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()
      }
    },

    // 转换身份
    changeUpdate(row) {
      this.changeShow = true
      this.editId = row.channelId
    },

    // 省
   /* 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();
    },
    /**关闭弹窗*/
    hideDialog(){
      this.createShow = false
      this.detailShow = false
      this.changeShow = 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.queryParams.parentId = parentId
      this.queryParams.parentName = title
      this.pageParams.pageNum = 1
      this.getList();
    },
  }
};
</script>
<style lang="sass" scoped>

</style>
