<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户电话" prop="userPhone">
        <el-input
          v-model="queryParams.userPhone"
          placeholder="请输入用户电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="快递单号" prop="deliverySn">
        <el-input
          v-model="queryParams.deliverySn"
          placeholder="请输入快递单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

       <el-form-item label="提交时间" prop="createTime">
                 <el-date-picker v-model="createTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="change"></el-date-picker>
              </el-form-item>
      <el-form-item label="销售公司" prop="companyId">
        <el-select v-model="queryParams.companyId" placeholder="销售公司"  size="small" @change="getAllUserlist(queryParams.companyId)" clearable>
          <el-option
            v-for="dict in qwCompanyList"
            :key="dict.companyId"
            :label="dict.companyName"
            :value="dict.companyId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售账号" prop="userId">
        <el-select v-model="queryParams.companyUserId" placeholder="销售账号"  size="small" clearable>
          <el-option
            v-for="dict in companyUserNameList"
            :key="dict.userId"
            :label="dict.userName"
            :value="dict.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="企微微信" prop="companyUserName">
        <el-select v-model="queryParams.qwUserId" placeholder="企微微信"  size="small" clearable>
          <el-option
            v-for="dict in qwUserList"
            :key="dict.id"
            :label="dict.qwUserName"
            :value="dict.id"
          />
        </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="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:integralOrder:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['his:integralOrder:exportDeliver']"
        >导入发货</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-tabs type="card" v-model="actName" @tab-click="handleClickX">
      <el-tab-pane label="全部订单" name="10"></el-tab-pane>
      <el-tab-pane v-for="(item,index) in statusOptions" :label="item.dictLabel" :name="item.dictValue"></el-tab-pane>
    </el-tabs>
    <el-table v-loading="loading" border :data="integralOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderCode" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="用户电话" align="center" prop="userPhone" />
      <el-table-column label="用户地址" align="center" prop="userAddress" show-overflow-tooltip />
      <el-table-column label="支付积分" align="center" prop="integral" />
      <el-table-column label="支付金额" align="center" prop="payMoney" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="快递公司编号" align="center" prop="deliveryCode" />
      <el-table-column label="快递名称" align="center" prop="deliveryName" />
      <el-table-column label="快递单号" align="center" prop="deliverySn" />
      <el-table-column label="发货时间" align="center" prop="deliveryTime" width="180"/>
      <el-table-column label="提交时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="所属公司" align="center" prop="companyName" width="180" show-overflow-tooltip/>
      <el-table-column label="所属销售" align="center" prop="companyUserNickName" width="180" show-overflow-tooltip/>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
             size="mini"
             type="text"
             @click="handledetails(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-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderCode">
          <el-input v-model="form.orderCode" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="用户id" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户id" />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户电话" prop="userPhone">
          <el-input v-model="form.userPhone" placeholder="请输入用户电话" />
        </el-form-item>
        <el-form-item label="用户地址" prop="userAddress">
          <el-input v-model="form.userAddress" placeholder="请输入用户地址" />
        </el-form-item>
        <el-form-item label="商品信息" prop="itemJson">
          <el-input v-model="form.itemJson" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="支付积分" prop="integral">
          <el-input v-model="form.integral" placeholder="请输入支付积分" />
        </el-form-item>
        <el-form-item label="1：待发货；2：待收货；3：已完成" prop="status">
          <el-select v-model="form.status" placeholder="请选择1：待发货；2：待收货；3：已完成">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司编号" prop="deliveryCode">
          <el-input v-model="form.deliveryCode" placeholder="请输入快递公司编号" />
        </el-form-item>
        <el-form-item label="快递名称" prop="deliveryName">
          <el-input v-model="form.deliveryName" placeholder="请输入快递名称" />
        </el-form-item>
        <el-form-item label="快递单号" prop="deliverySn">
          <el-input v-model="form.deliverySn" placeholder="请输入快递单号" />
        </el-form-item>
        <el-form-item label="发货时间" prop="deliveryTime">
          <el-date-picker clearable size="small"
            v-model="form.deliveryTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择发货时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
    	:with-header="false"
            size="75%"
             :title="show.title" :visible.sync="show.open">
         <integralOrderDetails  ref="Details" />
       </el-drawer>
   <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
         <el-upload
           ref="upload"
           :limit="1"
           accept=".xlsx, .xls"
           :headers="upload.headers"
           :action="upload.url + '?updateSupport=' + upload.updateSupport"
           :disabled="upload.isUploading"
           :on-progress="handleFileUploadProgress"
           :on-success="handleFileSuccess"
           :auto-upload="false"
           drag
         >
           <i class="el-icon-upload"></i>
           <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
           <div class="el-upload__tip text-center" slot="tip">
             <div class="el-upload__tip" slot="tip">
             </div>
             <span>仅允许导入xls、xlsx格式文件。</span>
             <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
           </div>
         </el-upload>
       <div slot="footer" class="dialog-footer">
         <el-button type="primary" @click="submitFileForm">确 定</el-button>
         <el-button @click="upload.open = false">取 消</el-button>
       </div>
     </el-dialog>
  </div>
</template>

<script>
import {importTemplate, listIntegralOrder,importExpressTemplate, getIntegralOrder, delIntegralOrder, addIntegralOrder, updateIntegralOrder, exportIntegralOrder } from "@/api/hisStore/integralOrder";
import integralOrderDetails from '../components/integralOrderDetails.vue';
import { getToken } from "@/utils/auth";
import {getCompanyList} from "@/api/company/company";
import {getAllUserlist} from "@/api/company/companyUser";
import {getQwUserInfo} from "@/api/qw/qwUser";

export default {
  name: "IntegralOrder",
  components: { integralOrderDetails },
  data() {
    return {
      show:{
              open:false,
            },
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/his/integralOrder/importData"
      },
      // 遮罩层
      loading: true,
      actName:"10",
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 积分商品订单表格数据
      integralOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 1：待发货；2：待收货；3：已完成字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        userName: null,
        userPhone: null,
        integral: null,
        status: null,
        deliverySn: null,
        createTime: null,
        sTime:null,
        eTime:null,
        companyUserId:null,
        qwUserId:null,
        companyId:null,
      },
       createTime:null,
      qwCompanyList:[],
      companyUserNameList:[],
      qwUserList:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户id不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "1：待发货；2：待收货；3：已完成不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_integral_order_status").then(response => {
      this.statusOptions = response.data;
    });


    //获取企业
    getCompanyList().then(response => {
      this.qwCompanyList = response.data;
    });
  },
  methods: {
    change(){
          if(this.createTime!=null){
            this.queryParams.sTime=this.createTime[0];
            this.queryParams.eTime=this.createTime[1];
          }else{
            this.queryParams.sTime=null;
            this.queryParams.eTime=null;
          }

        },
    handleImport() {
        this.upload.title = "导入";
        this.upload.open = true;
       },
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handledetails(row){
        this.show.open=true;
        setTimeout(() => {
             this.$refs.Details.getDetails(row.orderId);
        }, 1);
    },
    /** 查询积分商品订单列表 */
    getList() {
      this.loading = true;
      listIntegralOrder(this.queryParams).then(response => {
        this.integralOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderCode: null,
        userId: null,
        userName: null,
        userPhone: null,
        userAddress: null,
        itemJson: null,
        integral: null,
        status: null,
        deliveryCode: null,
        deliveryName: null,
        deliverySn: null,
        deliveryTime: null,
        createTime: null,
        remark: null,
        sTime:null,
        eTime:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createTime=null;
      this.queryParams.sTime=null;
      this.queryParams.eTime=null;
      this.queryParams.qwUserId=null;
      this.queryParams.companyId=null;
      this.queryParams.companyUserId=null;
      this.handleQuery();

    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加积分商品订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getIntegralOrder(orderId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改积分商品订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateIntegralOrder(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addIntegralOrder(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleClickX(tab, event) {
     if(tab.name=="10"){
       this.queryParams.status=null;
     }else{
       this.queryParams.status=tab.name;
     }
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$confirm('是否确认删除积分商品订单编号为"' + orderIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delIntegralOrder(orderIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有积分商品订单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportIntegralOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    //选择企业后触发
    getAllUserlist(companyId){
      if(companyId){
        getAllUserlist({companyId}).then(response => {
          this.companyUserNameList=response.data;
        });
        //企业微信
        getQwUserInfo({companyId}).then(response => {
          this.qwUserList=response.data;
        })
      }
    }
  }
};
</script>
