<template>
  <div class="app-container myapp-container">

    <!-- 筛选条件 -->
    <div class="screen-container">
      <div class="top clearfix">
        <div class="title fl">条件筛选</div>
      </div>
      <el-form ref="screenForm" :model="screenForm" label-width="85px" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="销售员姓名" prop="name">
              <el-input v-model="screenForm.name" placeholder="请输入销售员姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="screenForm.phone" placeholder="请输入手机号" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="销售额上限" prop="maxAmount">
              <el-input v-model="screenForm.maxAmount" placeholder="请输入销售额上限" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="销售额下限" prop="minAmount">
              <el-input v-model="screenForm.minAmount" placeholder="请输入销售额下限" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="状态" prop="state">
              <el-select v-model="screenForm.status" placeholder="全部">
                <el-option label="全部" value=""></el-option>
                <el-option :label="item.label" :value="item.value" v-for="(item, index) in select_status" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="网点名称" prop="websitNumber">
              <el-select v-model="screenForm.websitNumber" placeholder="全部" filterable>
                <el-option label="全部" value=""></el-option>
                <el-option :label="item.name" :value="item.websitNumber" v-for="(item, index) in websiteList" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="销售时间" prop="saleDate">
              <el-date-picker
                v-model="screenForm.saleDate"
                type="datetimerange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          
          <el-col :xs="24" :sm="12" :lg="6" class="tr">
            <el-form-item label="">
              <el-button size="small" @click="resetScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="mymain-container">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addOrEdit('add')">添加</el-button>
        </div>
        <div class="fr">
          <el-button size="small" type="primary" @click="handleExport">导出数据</el-button>
        </div>
      </div>

      <div class="table">
        <el-table ref="multipleTable" v-loading="listLoading" :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe>
          <el-table-column align="center" label="操作" min-width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="addOrEdit('edit', scope.row.id)">编辑</el-button>
              <el-popconfirm style="margin-left: 10px;" title="确定删除吗？" @onConfirm="handleDelete(scope.row.id)">
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column align="center" label="网点" prop="websitNumber" min-width="240" show-overflow-tooltip>
            <template slot-scope="scope">
              【{{scope.row.websitNumber}}】{{scope.row.websitName}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="区域" prop="zoneName" min-width="80"></el-table-column>
          <el-table-column align="center" label="销售员姓名" prop="saleManName" min-width="100"></el-table-column>
          <el-table-column align="center" label="销售员手机号" prop="salePhone" min-width="120"></el-table-column>
          <el-table-column align="center" label="销售金额" prop="saleAmount"></el-table-column>
          <el-table-column align="center" label="销售数量" prop="saleNum"></el-table-column>
          <el-table-column align="center" label="销售日期" prop="saleTime" min-width="160"></el-table-column>
          <el-table-column align="center" label="销售类型" prop="saleType">
            <template slot-scope="scope">
              {{scope.row.saleType | OFFLINE_TYPE_FILTER}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="商品类型" prop="goodsCategory" min-width="120" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="商品名称" prop="goodsName" min-width="120" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="状态" prop="status">
            <template slot-scope="scope">
              {{scope.row.status | OFFLINE_STATUS_FILTER}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="创建时间" prop="createTime" min-width="160"></el-table-column>
        </el-table>
      </div>

      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 新增编辑 -->
    <el-dialog :title="addFormType === 'add' ? '新增':'编辑'" :visible.sync="addFormVisible" :show-close="false" width="50%" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="left" label-width="110px">
        <el-form-item label="网点名称" prop="websitNumber">
          <el-select v-model="addForm.websitNumber" placeholder="全部" filterable style="width: 100%;">
            <el-option :label="item.name" :value="item.websitNumber" v-for="(item, index) in websiteList" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域名称" prop="zoneId">
          <el-select v-model="addForm.zoneId" placeholder="全部" filterable style="width: 100%;">
            <el-option :label="item.zoneName" :value="item.id" v-for="(item, index) in zoneList" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售员姓名" prop="saleManName">
          <el-input v-model="addForm.saleManName" autocomplete="off" placeholder="请输入销售员姓名"></el-input>
        </el-form-item>
        <el-form-item label="销售员手机号" prop="salePhone">
          <el-input v-model="addForm.salePhone" autocomplete="off" placeholder="请输入销售员手机号" type="number"></el-input>
        </el-form-item>
        <el-form-item label="销售日期" prop="saleTime">
          <el-date-picker v-model="addForm.saleTime" type="datetime" placeholder="请选择销售日期" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item label="销售类型" prop="saleType">
          <el-select v-model="addForm.saleType" placeholder="请选择销售类型" style="width: 100%;">
            <el-option :label="item.label" :value="item.value" v-for="(item, index) in select_type" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型" prop="goodsCategory">
          <el-select v-model="addForm.goodsCategory" placeholder="请选择商品类型" style="width: 100%;">
            <el-option :label="item" :value="item" v-for="(item, index) in goods_type" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="addForm.goodsName" autocomplete="off" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="销售金额" prop="saleAmount">
          <el-input v-model="addForm.saleAmount" autocomplete="off" placeholder="请输入销售金额" type="number"></el-input>
        </el-form-item>
        <el-form-item label="销售数量" prop="saleNum">
          <el-input v-model="addForm.saleNum" autocomplete="off" placeholder="请输入销售数量" type="number"></el-input>
        </el-form-item>
        <el-form-item label="凭证" prop="picUrl">
          <el-upload
            class="avatar-uploader"
            style="height:122px"
            :action="baseURL + 'common/upload'"
            :headers="myHeaders"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="addForm.picUrl" :src="addForm.picUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="addForm.remark" :autosize="{ minRows: 4, maxRows: 6}" autocomplete="off" placeholder="请输入备注"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddForm">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { getToken } from '@/utils/auth'
import { COMMON_SELECT } from '@/utils/select_data'
import { addData, deleteData, editData, getList, getDetail, getWebsiteList, getZoneList } from "@/api/offline";
import { downloadFiles } from '@/utils/util'

export default {
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: {'x-token': getToken()},
      dataList: null, // 列表数据
      listLoading: true, // 列表加载loading
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      screenForm: { // 筛选表单数据
        name: '',
        phone: '',
        maxAmount: '',
        minAmount: '',
        status: '',
        websitNumber: '',
        saleDate: [],
      },
      editId:  null,
      addFormType: 'add',
      addFormVisible: false,
      addForm: {
        websitNumber: '',
        zoneId: '',
        saleManName: '',
        salePhone: '',
        saleAmount: '',
        saleNum: '',
        saleTime: '',
        saleType: '',
        goodsCategory: '',
        goodsName: '',
        picUrl: '',
        remark: '',
      },
      addFormRules: {
        websitNumber: [
          { required: true, message: '请选择网点', trigger: 'change' }
        ],
        zoneId: [
          { required: true, message: '请选择区域', trigger: 'change' }
        ],
        saleManName: [
          { required: true, message: '请输入销售员姓名', trigger: 'blur' }
        ],
        salePhone: [
          { required: true, message: '请输入销售员手机号', trigger: 'blur' }
        ],
        saleAmount: [
          { required: true, message: '请输入销售金额', trigger: 'blur' }
        ],
        saleNum: [
          { required: true, message: '请输入销售数量', trigger: 'blur' }
        ],
        saleTime: [
          { required: true, message: '请选择销售日期', trigger: 'change' }
        ],
        saleType: [
          { required: true, message: '请选择销售类型', trigger: 'change' }
        ],
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
      },
      select_status: COMMON_SELECT.OFFLINE_STATUS,
      select_type: COMMON_SELECT.OFFLINE_TYPE,
      websiteList: [],
      zoneList: [],
      goods_type: ['空调', '热水器', '冰箱', '洗衣机', '净水机', '厨大电', '生活电器'],
    }
  },
  created() {
    this.getList();
    this.getWebsiteList();
    this.getZoneList();
  },
  methods: {
    // 网点列表
    getWebsiteList() {
      getWebsiteList().then(res => {
        this.websiteList = res.data;
      })
    },

    // 区域列表
    getZoneList() {
      getZoneList().then(res => {
        this.zoneList = res.data;
      })
    },

    getList() {
      this.listLoading = true;

      let params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        name: this.screenForm.name,
        phone: this.screenForm.phone,
        maxAmount: this.screenForm.maxAmount,
        minAmount: this.screenForm.minAmount,
        status: this.screenForm.status,
        websitNumber: this.screenForm.websitNumber,
        zoneId: this.screenForm.zoneId || '',
        startTime: this.screenForm.saleDate.length > 0 ? this.screenForm.saleDate[0] : '',
        endTime: this.screenForm.saleDate.length > 0 ? this.screenForm.saleDate[1] : '',
      };
      
      getList(params).then(res => {
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        this.listLoading = false;
      })
    },

    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1;
      this.getList();
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields();
      this.currentPage = 1;
      this.getList();
    },

    // 筛选后重新获取列表
    getListByScreen() {
      this.currentPage = 1;
      this.getList();
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },

    // 操作 - 删除
    handleDelete(id) {
      deleteData({id: id}).then(() => {
        this.getList();
        this.$successMsg();
      })
    },

    // 新增编辑
    addOrEdit(type, id) {
      this.addFormType = type;
      this.addFormVisible = true;
      if(type == 'edit') {
        this.editId = id;
        getDetail({id: id}).then(res => {
          this.addForm = {
            websitNumber: res.data.websitNumber,
            zoneId: res.data.zoneId,
            saleManName: res.data.saleManName,
            salePhone: res.data.salePhone,
            saleAmount: res.data.saleAmount,
            saleNum: res.data.saleNum,
            saleTime: res.data.saleTime,
            saleType: res.data.saleType,
            goodsCategory: res.data.goodsCategory,
            goodsName: res.data.goodsName,
            picUrl: res.data.picUrl,
            remark: res.data.remark,
          }
        })
      }else {
        console.log(this.$store.state.user);
        this.addForm.saleManName = this.$store.state.user.name;
        this.addForm.salePhone = this.$store.state.user.phone;
      }
    },

    // 取消 新增编辑
    cancelAddForm(){
      this.addFormVisible = false;
      this.$refs.addForm.resetFields();
    },

    // 提交 新增编辑
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let websitName = this.websiteList[this.$findElem(this.websiteList, 'websitNumber', this.addForm.websitNumber)].name;
          let zoneName = this.zoneList[this.$findElem(this.zoneList, 'id', this.addForm.zoneId)].zoneName;

          let params = {
            websitName,
            websitNumber: this.addForm.websitNumber,
            zoneName,
            zoneId: this.addForm.zoneId,
            saleManName: this.addForm.saleManName,
            salePhone: this.addForm.salePhone,
            saleAmount: this.addForm.saleAmount,
            saleNum: this.addForm.saleNum,
            saleTime: this.addForm.saleTime,
            saleType: this.addForm.saleType,
            goodsCategory: this.addForm.goodsCategory,
            goodsName: this.addForm.goodsName,
            picUrl: this.addForm.picUrl,
            remark: this.addForm.remark,
          }
          if(this.addFormType == 'edit') {
            params.id = this.editId;
            editData(params).then(res => {
              this.cancelAddForm();
              this.getList();
              this.$successMsg('编辑成功');
            })
          } else {
            addData(params).then(res => {
              this.cancelAddForm();
              this.getList();
              this.$successMsg('新增成功');
            })
          }
        }
      })
    },

    uploadSuccess(res, file) {
      this.addForm.picUrl = res.data.url;
    },

    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ['jpg', 'jpeg', 'png'];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg('只支持上传jpg/jpeg/png文件!');
        return false;
      }
    },

    // 导出
    handleExport() {
      let screenData = {
        name: this.screenForm.name,
        phone: this.screenForm.phone,
        maxAmount: this.screenForm.maxAmount,
        minAmount: this.screenForm.minAmount,
        status: this.screenForm.status,
        websitNumber: this.screenForm.websitNumber,
        zoneId: this.screenForm.zoneId || '',
        startTime: this.screenForm.saleDate.length > 0 ? this.screenForm.saleDate[0] : '',
        endTime: this.screenForm.saleDate.length > 0 ? this.screenForm.saleDate[1] : '',
      };
      downloadFiles('offline/export', screenData);
    },
  }
}
</script>

<style lang="scss">
  .myapp-container input::-webkit-outer-spin-button,
  .myapp-container input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
  }
  .myapp-container input[type='number'] {
    -moz-appearance: textfield !important;
  }
</style>
