<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> -->
      <el-col :span="1.5">
        <el-button
          type="infor"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleOrderExport"
          v-hasPermi="['business:salesite:export']"
        >导出门店</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="siteList" @sort-change="sortChannelId" @selection-change="handleSelectionChange">
     <!-- <el-table-column type="selection" width="55"  /> -->
      <el-table-column label="门店编号" sortable="custom" prop="channelId" width="110px"/>
      <el-table-column label="门店名称" show-overflow-tooltip  prop="name" min-width="110px" >
        <template slot-scope="scope">
          <pre>{{scope.row.name}}</pre>
        </template>
      </el-table-column>
      <el-table-column label="手机号码"  prop="mobile" width="120px"/>
      <el-table-column label="佣金比例" sortable="custom" prop="commRate" width="100px">
        <template slot-scope="{ row, column }">
           <span>{{row.commRate}}%</span>
        </template>
      </el-table-column>
      <el-table-column label="上级渠道" prop="parentsName" min-width="100px" />
      <el-table-column label="盲票库存" sortable="custom" prop="offLineQtyCnt" width="100px"/>
      <el-table-column label="线下销量" sortable="custom" prop="offLineSaleCnt" width="100px"/>
      <el-table-column label="线上销量" sortable="custom" prop="onLineSaleCnt" width="100px"/>
      <el-table-column label="用户数" sortable="custom" prop="userCnt" width="100px"/>
      <el-table-column label="注册时间" prop="createdTime" width="150px">
        <template slot-scope="{ row }">
          {{ parseTime(row.createdTime) }}
        </template>
      </el-table-column>
      <el-table-column label="认证状态" 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="状态" 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>
        <!-- <template slot-scope="scope">
          <el-switch
            v-model="scope.row.statusV"
            active-value="1"
            inactive-value="2"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </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"
            @click="handleDetail(scope.row)"
            v-hasPermi="['business:salesite:query']"
          >查看</el-button>

         <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:salesite:edit']"
          >编辑</el-button>
        <el-button
            size="mini"
            type="text"
            @click="handleStatusChange(scope.row)"
            v-hasPermi="['business:salesite: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"
            @change="handleStatusChange(scope.row)"
             v-hasPermi="['business:salesite:edit']"
          ></el-switch> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pageParams.pageNum"
      :limit.sync="pageParams.pageSize"
      @pagination="getList"
    />

    <!-- 新建 -->
    <add-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,salesiteOrderExport } from "@/api/admin/salesite";
import SiteCreate from './components/Create'
import AddSiteCreate from './components/AddCreate'
import SiteDetail from './components/Detail'
export default {
  name: "Salesite",
  components: {
    AddSiteCreate,
    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,
      // 门店表格数据
      siteList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        parentId: "",
        name: "",
        mobile: "",
        provinceId:"",
        cityId:"",
        areaId:""
      },
      pageParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 't1.channelId',
        isAsc: 'desc',
      },
      // 表单参数
      form: {},

    };
  },
  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+'&orderByColumn='+ this.pageParams.orderByColumn +'&isAsc='+ this.pageParams.isAsc +'&',this.queryParams).then(response => {
        this.siteList = response.rows;
        this.siteList.forEach(item => {
            item.statusV = JSON.parse(item.status).value+""
        })
        this.total = response.total;
        this.loading = false;
      });
    },

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

    // 获取上级渠道下拉列表
    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 => {
         this.provinceList = response || [];
      });
    },

    // 导出订单
    handleOrderExport() {
      this.$confirm("是否确认导出门店?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.vloading = this.$loading({
            lock: true,
            text: "正在导出订单.....",
            background: "rgba(0, 0, 0, 0.7)",
          });
          return salesiteOrderExport(this.queryParams);
        })
        .then((response) => {
          this.vloading.close();
          this.download(response.msg);
        })
        .catch(() => {
          this.vloading.close();
        });
    },

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

    getAreaList(){
      var cityId = this.queryParams.cityId
      listAreaByPid(cityId).then(response => {
         this.areaList = response || [];
      });
    },


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


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

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

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

    /** 搜索按钮操作 */
    handleQuery() {
      this.channelList = this.channelCopyList;
      this.pageParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams= {
         parentId: "",
         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
    },

    handleDetail(row){
      this.detailShow = true
      this.editId = row.channelId
    },
    /** 新增按钮操作 */
    handleAdd() {
       this.createShow = true
       this.editId = null
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.editId = row.channelId
      this.createShow = true
    },

    // 保存后的操作
    submitSuccess(){
      this.getList();
    },

    /**关闭弹窗*/
    hideDialog(){
      this.createShow = false
      this.detailShow = false
    },

    // 状态修改
    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.statusV = row.statusV === "1" ? "2" : "1";
        });
    }
  }
};
</script>
