<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="人员姓名" prop="promoterUserName">
        <el-input v-model="queryParams.promoterUserName" placeholder="请输入人员姓名" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="promoterUserPhone">
        <el-input v-model="queryParams.promoterUserPhone" maxlength="11" placeholder="请输入手机号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="enableStatus">
        <el-select v-model="queryParams.enableStatus" placeholder="请输入状态" clearable size="small" style="width: 240px">
          <el-option label="正常" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="daterangeCreateTime" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="所在区域" prop="provinces">
        <el-cascader ref="refSubCat" size="small" v-model="queryParams.provinces" placeholder="请选择所在区域" :options="areaTrea" :props="{ expandTrigger: 'hover' }" @change="queryParamshandleChange" style="width: 100%"></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <!-- <el-button type="primary" icon="el-icon-search" size="mini" @click="handlePage">搜索(自定义分页接口)</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" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="index" width="55" label="序号" align="center">
        <template slot-scope="scope">
          <div>
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="人员姓名" align="center" prop="promoterUserName" />
      <el-table-column label="手机号" align="center" prop="promoterUserPhone" />
      <el-table-column label="所在区域" align="center" prop="adName">
        <template slot-scope="{row}">
          <div>
            {{ row.provinceName+row.cityName+row.districtName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="地推地点" prop="promotionLocation" align="center" />
      <el-table-column label="所属商家" prop="merchantName" align="center" />
      <el-table-column label="累计佣金" align="center" prop="moneyTotal" />
      <el-table-column label="状态" align="center" prop="enableStatus">
        <template slot-scope="{row}">
          <el-tag type="success" v-if="row.enableStatus">启用</el-tag>
          <el-tag type="danger" v-if="!row.enableStatus">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</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" @click="handleUpdate(scope.row,'show')">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,'edit')">编辑</el-button>
          <el-button size="mini" type="text" @click="setStatus(scope.row)">{{scope.row.enableStatus?'禁用':'启用'}}</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改测试单表对话框 -->
    <el-drawer :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :disabled="title=='查看地推人员'" :rules="rules" label-width="120px">
        <el-form-item label="选择人员" prop="promoterUserName">
          {{form.promoterUserName}}
          <el-button type="primary" v-if="title!='查看地推人员'" size="small" icon="el-icon-plus" @click="openSelUser()">选择</el-button>
        </el-form-item>
        <el-form-item label="手机号" prop="promoterUserPhone">
          <el-input v-model="form.promoterUserPhone" disabled maxlength="11" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item label="所属区域" prop="areaArr">
          <el-cascader ref="refSubCat" v-model="form.areaArr" placeholder="请选择所属区域" :options="areaTrea" :props="{ expandTrigger: 'hover' }" @change="handleChange" style="width: 100%"></el-cascader>
        </el-form-item>
        <el-form-item label="地推地点" prop="promotionLocation">
          <el-input v-model="form.promotionLocation" placeholder="请输入地推地点" maxlength="50" clearable />
        </el-form-item>
        <el-form-item label="所属商家" prop="merchantId">
          <el-select v-model="form.merchantId" filterable placeholder="请选择所属商家" clearable style="width: 100%" @change="merchantIdChange">
            <el-option v-for="(v,i) in shopList" :key="i" :label="v.businessName" :value="v.businessId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="demo-drawer__footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="title!='查看地推人员'">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-drawer>
    <selUser ref="selUserRef" @result="result" />
  </div>
</template>

<script>
import { cnAreaTree, businessList } from '@/api/shop'
import { fieldPromotionAdd, fieldPromotionEdit, fieldPromotionPage, fieldPromotionDel, fieldPromotionInfo, fieldPromotionStatus } from "@/api/distribute.js";
import { getToken } from "@/utils/auth";
import selUser from '@/components/SelUser'

export default {
  dicts: ['ad_location'],
  components: {
    selUser
  },
  data () {
    return {
      //按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试单表表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 创建时间时间范围
      daterangeCreateTime: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "添加广告",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/demo/demo/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        promoterUserPhone: undefined,
        promoterUserName: undefined,
        provinces: [],
        cityCode: undefined,
        areaCode: undefined,
        merchantId: undefined,
        enableStatus: undefined
      },
      // 表单参数
      form: {
        promoterUserName: undefined,
        promoterUserPhone: undefined,
        provinces: undefined,
        promotionLocation: undefined,
        merchantId: undefined,
        provinceCode: undefined,
        cityCode: undefined,
        areaCode: undefined,
        areaArr: []
      },
      // 表单校验
      rules: {
        promoterUserName: [
          { required: true, message: "请输入人员名称", trigger: "blur" }
        ],
        promoterUserPhone: [
          { required: true, message: "请输入手机号", trigger: "blur" }
        ],
        areaArr: [
          { required: true, message: "请选择所属区域", trigger: "blur" }
        ],
        promotionLocation: [
          { required: true, message: "请输入地推地点", trigger: "blur" }
        ],
        merchantId: [{ required: true, message: "请选择所属商家", trigger: "change" }],
      },
      jumpTypeList: [
        { label: "内部页面", value: 0 },
        { label: "外部链接", value: 1 },
        { label: "内部资源", value: 2 },
      ],
      resourceTip: [
        { label: "应用", value: 1 },
        { label: "主题", value: 2 },
        { label: "新闻", value: 3 },
        { label: "活动", value: 4 },
        { label: "地图分类", value: 5 },
      ],
      areaTrea: [],
      shopList: []
    };
  },
  created () {
    this.getList();
    this.getCnAreaTree();
    this.getShopList()
  },
  methods: {
    getShopList () {
      businessList().then(res => {
        this.shopList = res.data
      })
    },
    openSelUser () {
      this.$refs.selUserRef.open()
    },
    merchantIdChange (e) {
      this.form.merchantName = this.shopList.find(item => item.businessId == e).businessName
    },
    /** 查询测试单表列表 */
    getCnAreaTree () {
      cnAreaTree().then(res => {
        this.areaTrea = res.data?.children
      })
    },
    result (e) {
      this.form.promoterUserName = e.nickname;
      this.form.promoterUserId = e.id;
      this.form.promoterUserPhone = e.mobile;
    },
    getList () {
      this.loading = true;
      this.queryParams["createTimeStart"] = undefined;
      this.queryParams["createTimeEnd"] = undefined;
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams["createTimeStart"] = this.daterangeCreateTime[0];
        this.queryParams["createTimeEnd"] = this.daterangeCreateTime[1];
      }
      fieldPromotionPage(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 省市区选择
    handleChange (value) {
      if (value && value.length > 1) {
        this.form.provinces = value;
        this.form.provinceCode = value[0];
        this.form.provinceName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[0];
        this.form.cityCode = value[1];
        this.form.cityName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[1];
        this.form.districtCode = value[2];
        this.form.districtName = this.$refs['refSubCat'].getCheckedNodes()[0].pathLabels[2];
      }
    },
    queryParamshandleChange (value) {
      this.queryParams.provinces = value;
      this.queryParams.provinceCode = value[0];
      this.queryParams.cityCode = value[1];
      this.queryParams.districtCode = value[2];
    },
    handleResourceTip (type) {
      for (let item of this.resourceTip) {
        if (type == item.value) {
          return item.label || "";
        }
      }
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        promoterUserName: undefined,
        promoterUserPhone: undefined,
        provinces: undefined,
        promotionLocation: undefined,
        merchantId: undefined,
        provinceCode: undefined,
        cityCode: undefined,
        areaCode: undefined,
        promotionId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handlePage () {
      this.queryParams.pageNum = 1;
      this.getPage();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryParams.provinceCode = undefined;
      this.queryParams.cityCode = undefined;
      this.queryParams.districtCode = undefined;
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.adId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "新增地推人员";
    },
    /** 修改按钮操作 */
    handleUpdate (row, type) {
      this.loading = true;
      this.reset();
      const id = row.promotionId || this.ids
      fieldPromotionInfo(id).then(response => {
        this.loading = false;
        response.data.areaArr = [response.data.provinceCode, response.data.cityCode, response.data.districtCode];
        this.form = response.data;
        console.log(this.form)
        this.open = true;
        this.title = type == 'edit' ? "编辑地推人员" : "查看地推人员";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.promotionId) {
            fieldPromotionEdit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            fieldPromotionAdd(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.promotionId || this.ids;
      this.$modal.confirm('是否确认删除人员姓名为"' + row.promoterUserName + '"的数据项？').then(() => {
        this.loading = true;
        return fieldPromotionDel(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 上下架按钮操作 */
    setStatus (row) {
      const ids = row.promotionId || this.ids;
      let statusText = row.enableStatus ? '禁用' : '启用';
      this.$modal.confirm('是否确认' + statusText + '人员姓名为"' + row.promoterUserName + '"的数据项？').then(() => {
        this.loading = true;
        return fieldPromotionStatus({ promotionId: row.promotionId });
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess(statusText + "成功");
      }).finally(() => {
        this.loading = false;
      });
    },
  }
};
</script>
<style lang="scss">
.el-drawer__body {
  padding: 0 20px !important;
}
</style>
<style lang="scss" scoped>
.flex {
  display: flex;
}
.demo-drawer__footer {
  margin-left: 120px;
}
</style>
