<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="75px">
      <el-form-item label="上级渠道" prop="parentId">
        <el-select
          v-model="queryParams.parentId"
          placeholder="请选择上级渠道"
          style="width: 100%;"
          filterable
          clearable
          :filter-method="dataFilter"
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in channelList"
            :key="item.channelId"
            :label="item.name"
            :value="item.channelId">
            <div>
              <span style="float: left;">{{item.name}} </span>
              <span style="float: right;">{{item.mobile}}</span>
            </div>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="经销商名称" prop="name" label-width="90px">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入经销商名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号码"
          clearable
          size="small"
          @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"
          disabled=""
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
        >添加经销商</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
     <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="经销商ID" prop="channelId" />
      <el-table-column label="经销商名称" align="center" prop="name" />
      <el-table-column label="手机号码" align="center" prop="mobile" />
      <el-table-column label="佣金比例" align="center" prop="commRate" />
      <el-table-column label="用户数" align="center" prop="userCnt" />
      <el-table-column label="认证状态" align="center" prop="certifyStatus" >
        <template slot-scope="{ row, column }">
             <span v-if="getValue(row.certifyStatus) == 'y'" style="color: blue;"> {{getDesc(row.certifyStatus)}}</span>
             <span v-if="getValue(row.certifyStatus) == 'n'" style="color: red;"> {{getDesc(row.certifyStatus)}}</span>
         </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status"  >
         <template slot-scope="{ row, column }">
             <span v-if="getValue(row.status) == 1" style="color: blue;"> {{getDesc(row.status)}}</span>
             <span v-if="getValue(row.status) == 2" style="color: red;"> {{getDesc(row.status)}}</span>
         </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            disabled
            @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:salesite:read']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            disabled
            @click="handleUpdate(scope.row)"
            v-hasPermi="['admin:salesite:edit']"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleStatusChange(scope.row)"
            v-hasPermi="['admin:salesite:remove']"
          >

          <span v-if="getValue(scope.row.status) == 1"> 停用</span>
          <span v-if="getValue(scope.row.status) == 2"> 启用</span>

          </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"
    />

    <!-- 新建 -->
    <site-create
      v-if="createShow"
      :dialog-visible="createShow"
      :edit-id="editId"
      @saveSuccess="submitSuccess"
      @close="hideDialog"
    />

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

<script>
import { listAllChannel} from "@/api/admin/channel";
import { listAreaByPid} from "@/api/admin/area";
import { listSaleSite, updateSaleSiteStatus} from "@/api/admin/salesite";
import SiteCreate from './components/Create'
import SiteDetail from './components/Detail'
export default {
  name: "SaleSiteIndex",
  components: {
   SiteCreate,
   SiteDetail
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 创建编辑
      createShow: false,
      // 详情
      detailShow: false,
      // 编辑项ID
      editId: null,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 上级渠道列表
      channelList:[],
      channelCopyList:[],
      provinceList:[],
      cityList:[],
      areaList:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        parentId: "",
        name: "",
        mobile: "",
        provinceId:"",
        cityId:"",
        areaId:""
      },
      pageParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        postName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" }
        ],
        postCode: [
          { required: true, message: "岗位编码不能为空", trigger: "blur" }
        ],
        postSort: [
          { required: true, message: "岗位顺序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  mounted() {
    this.getChannelList()
    this.getProvinceList()
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
  },
  methods: {
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      listSaleSite('pageNum='+this.pageParams.pageNum + '&pageSize='+this.pageParams.pageSize+'&',this.queryParams).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取上级渠道下拉列表
    getChannelList(){
      listAllChannel().then(response => {
         this.channelList = response.data || [];
         this.channelCopyList = 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 || [];
      });
    },


    dataFilter(val) {
      this.value = val;
      if (val) { //val存在
        this.channelList = this.channelCopyList.filter((item) => {
          // console.log("dataFilter item"+JSON.stringify(item))
          if (!!~item.mobile.indexOf(val) || !!~item.mobile.toUpperCase().indexOf(val.toUpperCase())) {
             return true
          }
        })
      } else { //val为空时，还原数组
        this.channelList = this.channelCopyList;
      }
    },


    // 岗位状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },

    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) || "";
    },

    submitSuccess(){
      this.getList();
    },

    hideDialog(){
      this.createShow = false
      this.detailShow = false
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        postId: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: 0,
        status: "0",
        remark: undefined
      };
      this.cityList = []
      this.areaList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.channelList = this.channelCopyList;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams= {
         parentId: "",
         name: "",
         mobile: "",
         provinceId:"",
         cityId:"",
         areaId:""
      },
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.postId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
       this.createShow = true
       this.editId = null
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const postId = row.postId || this.ids
      getPost(postId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改岗位";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.postId != undefined) {
            updatePost(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPost(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.postId || this.ids;
      this.$confirm('是否确认删除名称为"' + row.name + '"的经销商?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPost(postIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },


    // 状态修改
    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 updateSaleSiteStatus(params);
        }).then(() => {
          this.msgSuccess(text + "成功");
          this.getList();
        }).catch(function() {
          // row.status = row.status === "0" ? "1" : "0";
        });
    }
  }
};
</script>
