<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="90px"
    >
      <el-form-item label="用户昵称">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          size="small"
          style="width: 240px"
          @change="pageParams.pageNum = 1;handleQuery()"
        />
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入商品名称"
          clearable
          size="small"
          style="width: 240px"
          @change="pageParams.pageNum = 1;handleQuery()"
        />
      </el-form-item>
      <el-form-item label="订单类型">
        <el-select
          v-model="queryParams.resource"
          placeholder="请选择订单类型"
          style="width: 240px"
          size="small"
          filterable
          clearable
          @change="pageParams.pageNum = 1;handleQuery()"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="提货订单" value="1"></el-option>
          <el-option label="现金购买" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单号">
        <el-input
          v-model="queryParams.orderId"
          placeholder="输入订单编号"
          clearable
          size="small"
          style="width: 240px"
          @change="pageParams.pageNum = 1;handleQuery()"
        />
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="tradeTimeArr"
          type="datetimerange"
          size="small"
          value-format="timestamp"
          range-separator="至"
          start-placeholder="时间选择"
          end-placeholder="时间选择"
          @change="tardeTime"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="收货人手机">
        <el-input
          v-model="queryParams.tel"
          placeholder="输入手机号"
          clearable
          size="small"
          style="width: 240px"
          @change="pageParams.pageNum = 1;handleQuery()"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplierId">
        <el-select v-model="queryParams.supplierId" placeholder="请选择供应商" filterable clearable  @clear="pageParams.pageNum = 1;handleQuery()" @change="pageParams.pageNum = 1;handleQuery()">
          <el-option :label="item.name" :value="item.id" v-for="(item, index) in SupplierList" :key="index" />
        </el-select>
      </el-form-item>
      <el-form-item label="付款方式" prop="payType">
        <el-select
          v-model="queryParams.payType"
          placeholder="请选择付款方式"
          style="width: 100%"
          size="small"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="微信" value="2"></el-option>
          <el-option label="支付宝" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="pageParams.pageNum = 1;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="infor"
          plain
          icon="el-icon-download"
          size="small"
          @click="handleExportDraw"
          v-hasPermi="['order:deliver:export']"
        >导出订单
        </el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="infor"
          plain
          icon="el-icon-upload2"
          size="small"
          @click="handleImport"
          v-hasPermi="['order:deliver:ship']"
        >批量发货
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="infor"
          plain
          icon="el-icon-position"
          size="small"
          @click="batchshortMessageFun"
          v-hasPermi="['order:deliver:ship']"
        >发送发货超时短信
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!-- 订单状态 -->
    <el-tabs type="card" v-model="state" @tab-click="handleClick">
      <el-tab-pane label="全部订单" name="no"></el-tab-pane>
      <el-tab-pane label="待付款" name="0"></el-tab-pane>
      <el-tab-pane label="待发货" name="1"></el-tab-pane>
      <el-tab-pane label="已发货" name="2"></el-tab-pane>
      <el-tab-pane label="部分发货" name="4"></el-tab-pane>
      <el-tab-pane label="已完成" name="3"></el-tab-pane>
      <el-tab-pane label="已取消" name="-1"></el-tab-pane>
    </el-tabs>
    <!-- 列表 -->
    <el-table ref="table" v-loading="loading" :data="list">
      <!-- 展开盲票组列表 -->
      <el-table-column type="expand">
        <template slot-scope="{ row,$index }">
          <el-table :data="row.items" row-key="itemId" @selection-change="handleSelectionChange( $event,row.orderId,row.tel )">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column label="商品图片" min-width="80">
              <div slot-scope="{ row }">
                <el-image
                  style="width: 100px; height: 100px"
                  :src="row.picUrl"
                  :preview-src-list="[row.picUrl]"
                />
              </div>
            </el-table-column>
            <el-table-column label="商品名称" prop="title" min-width="80"/>
            <el-table-column label="规格" min-width="100">
              <template slot-scope="{ row }">
                <div>{{ row.properties || "--" }}</div>
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="orderNum" min-width="85">
              <template slot-scope="{ row }">
                <div>{{ row.goodsNum }}件</div>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <!-- 不展开列表 -->
      <el-table-column label="订单号" prop="orderId" min-width="80"/>
      <el-table-column label="下单时间" min-width="100">
        <template slot-scope="{ row }">
          <div>
            {{ parseTime(row.createdTime) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="数量" prop="pkgNum" min-width="85">
        <template slot-scope="{ row }">
          <div>{{ row.orderNum }}件</div>
        </template>
      </el-table-column>
      <el-table-column label="实付金额(元)" min-width="85">
        <template slot-scope="{ row }">
          <div>{{ $numberFormat(row.payAmt) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="用户昵称" prop="nickName" min-width="80"/>
      <el-table-column label="收货人/收货地址" prop="addr" min-width="120">
        <template slot-scope="{ row }">
          <div>
            {{
              `${row.receiver}，${row.tel}，${row.province}${row.city}${row.area}${row.address}`
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单类型" prop="resource" min-width="70" align="center">
        <template slot-scope="{ row }">
          <div>{{ JSON.parse(row.resource).desc }}</div>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center">
        <template slot-scope="{ row }">
          <div>
            <el-tag :type="row.status.value === 1 ? 'success' : 'info'" v-if="row.status.value !== 2">{{
                row.status.desc
              }}
            </el-tag>
            <el-tag type="info" v-else>已发货</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="付款方式" min-width="95">
        <template slot-scope="{ row }">
          <div v-if="row.payType == '2'">微信</div>
          <div v-else-if="row.payType == '1' || row.payType == '10'">支付宝</div>
          <div v-else>--</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="80">
        <template slot-scope="{ row }">
          <div>
            <el-button
              v-hasPermi="['order:deliver:query']"
              type="text"
              @click="getDetail(row)"
            >查看详情
            </el-button
            >
            <el-button
              v-if="row.status.value === 1 || row.status.value === 4"
              v-hasPermi="['order:deliver:ship']"
              type="text"
              @click="toGoods(row)"
            >发货
            </el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body :before-close="openSwitch">
      <el-upload
        ref="upload"
        :limit="1"
        :data="reqData"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :http-request="reqUploadFile"
        :on-exceed="exceedMax"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入 xls xlsx 格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openSwitch">取 消</el-button>
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose">
      <div v-html="responseData"></div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>

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

    <!-- 发货 -->
    <send-goods :send-show="goodsShow" :goods-info="goodsInfo" @close="close"/>
  </div>
</template>
<script>
import {
  getDeliverList,
  deliverOrderExport, setBatchShip, batchshortMessage
} from "@/api/business/order";
import {publicFileGetUrl} from "@/api/common";
import {getToken, getSign} from "@/utils/auth";
import SendGoods from "./components/SendGoods";
import { randomStr20 } from '@/utils/util'
import { getSupplierList } from '@/api/business/supplier'
export default {
  name: "Deliver",
  components: {
    SendGoods,
  },
  data() {
    return {
      loading: false,
      showSearch: true,
      dialogVisible: false,
      // 筛选
      queryParams: {
        nickName: "",
        title: "",
        orderId: "",
        startTime: "",
        endTime: "",
        status: "",
        tel: "",
        supplierId: "",
        payType: "",
      },
      // 分页
      pageParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      list: [],
      // 门店
      merchantArr: [],
      // 下单时间
      tradeTimeArr: [],
      // 订单列表状态
      state: "no",
      // 发货显示
      goodsShow: false,
      // 订单详情
      goodsInfo: {},
      // 用户导入参数
      upload: {
        open: false,// 是否显示弹出层（用户导入）
        title: "",// 弹出层标题（用户导入）
        isUploading: false,// 是否禁用上传
        url: "",// 上传的地址
        headers: {},//请求头
      },
      fileSaveUrl: '',
      reqData: {},
      responseData:'',
      SupplierList: [],
      changeDate:[],//全部所选的商品
    };
  },
  created() {
    this.getList();
    this.getSupplierItems()
  },
  methods: {
    handleSelectionChange(goodsNameList,orderId,mobile) {
      let arr = []
      for (let i = 0; i < goodsNameList.length; i++) {
        arr = [...arr,goodsNameList[i].title]
      }
      for(let i = 0;i < this.changeDate.length; i++ ){
        if(this.changeDate[i].orderId == orderId){
          this.changeDate[i].goodsNameList = arr
          return
        }
      }
      let data = {
        goodsNameList: arr,
        orderId,
        mobile
      }
      this.changeDate.push(data)
    },
    //获取供应商
    getSupplierItems(){
      getSupplierList('',{}).then(res => {
        this.SupplierList = res && res.rows
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
      // 订单列表
    getList() {
      this.changeDate = []
      let data = {
        ...this.queryParams,
        resource: Number(this.queryParams.resource)
      }
      this.loading = true;
      getDeliverList(
        "pageNum=" +
        this.pageParams.pageNum +
        "&pageSize=" +
        this.pageParams.pageSize +
        "&",
        data
      )
        .then((res) => {
          this.loading = false;
          if (res.code == 0) {
            res.rows.forEach((item) => {
              let items = item.items;
              items.forEach((item) => {
                let picUrlArr = item.picUrl.split(",");
                item.picUrl = publicFileGetUrl + picUrlArr[0];
              });
              item.status = JSON.parse(item.status);
            });
            this.total = res.total;
            this.list = res.rows;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },

    //搜索
    handleQuery() {
      this.getList();
    },

    //请求头
    getHttpHeader() {
      let timestamp = parseInt(new Date().getTime()),
        nonce = randomStr20();
      var sign = getSign(this.reqData || {}, timestamp)
      let url = process.env.VUE_APP_BASE_API + '/api/v1/mp/admin/deliver/order/batchShip' + '?sign=' + sign + '&nonce=' + nonce;
      this.upload.url = url
      var headers = {
        "Authorization": "Bearer " + getToken(),
        "x-zz-timestamp": timestamp
      }
      this.upload.headers = headers
    },

    // 自定义文件上传的实现
    reqUploadFile(param) {
      var data = this.reqData || {}
      var params = {
        file: param.file,
        ...data
      }
      setBatchShip(params, this.headers).then(response => {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if(response.data){
          this.responseData = response.data
          this.dialogVisible = true
          // this.$alert(response.data, "导入结果", { dangerouslyUseHTMLString: true, customClass: 'msgbox' });
        }
        this.close()
      }).catch(response => {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if(response.data){
          this.responseData = response.data
          this.dialogVisible = true
          // this.$alert(response.data, "导入结果", { dangerouslyUseHTMLString: true, customClass: 'msgbox'  });
        }
        this.vloading.close();
        //param.onError()
      })
    },

    //导入按钮操作
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
      this.getHttpHeader()
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.getList();
    },
    // 超出限制时的提示
    exceedMax() {
      this.$message({
        message:  '请移除已有文件后再进行上传',
        type: 'warning'
      })
    },
    openSwitch(){
      this.upload.open = false
      this.$refs.upload.clearFiles();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    // 重置
    resetQuery() {
      this.queryParams = {
        nickName: "",
        title: "",
        orderId: "",
        startTime: "",
        endTime: "",
        status: "",
        tel: "",
        supplierId: "",
        payType: "",
      };
      this.state = "no"
      this.tradeTimeArr = [];
      this.getList();
    },

    // 选择下单时间
    tardeTime(e) {
      if (e) {
        this.queryParams.startTime = e[0];
        this.queryParams.endTime = e[1];
        this.pageParams.pageNum = 1
        this.handleQuery();
      } else {
        this.queryParams.startTime = "";
        this.queryParams.endTime = "";
        this.pageParams.pageNum = 1
        this.handleQuery();
      }
    },

    // 订单切换
    handleClick(e) {
      if (e.name == "no") {
        this.queryParams.status = "";
      } else {
        this.queryParams.status = Number(e.name);
      }
      this.getList();
    },

    // 查看详情
    getDetail(row) {
      this.$router.push({name: "DeliverDetail", query: {id: row.orderId}});
    },

    // 点击发货
    toGoods(row) {
      this.goodsShow = true;
      this.goodsInfo = row;
    },

    // 关闭发货
    close() {
      this.goodsShow = false;
      this.getList();
    },
    // 批量短信
    batchshortMessageFun() {
      for (let i = 0; i < this.changeDate.length; i++) {
        if(this.changeDate[i].goodsNameList.length == 0) {
          this.changeDate.splice(i,1)
        }
      }
      if (this.changeDate.length == 0) {
        this.$message.warning('请先选择商品');
        return;
      }
      let num = 0
      for (let i = 0; i < this.changeDate.length; i++) {
        num = num + this.changeDate[i].goodsNameList.length
      }
      this.$confirm(`您确定要发送${num}条发货超时短信吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          this.vloading = this.$loading({
            lock: true,
            text: "正在发送短信.....",
            background: "rgba(0, 0, 0, 0.7)",
          });

          return batchshortMessage(this.changeDate);
        })
        .then((response) => {
          this.vloading.close();
          this.getList();
          this.$message.success('短信发送成功');
        })
        .catch(() => {
          this.vloading.close();
        });
    },

    // 导出订单
    handleExportDraw() {
      let data = {
        ...this.queryParams,
        resource: this.queryParams.resource == '' ? this.queryParams.resource : Number(this.queryParams.resource),
      }
      this.$confirm("是否确认导出订单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.vloading = this.$loading({
            lock: true,
            text: "正在导出订单.....",
            background: "rgba(0, 0, 0, 0.7)",
          });
          return deliverOrderExport(data);
        })
        .then((response) => {
          this.vloading.close();
          this.download(response.msg);
        })
        .catch(() => {
          this.vloading.close();
        });
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-tabs--border-card > .el-tabs__content {
  padding: 0;
}

</style>
<style  lang="scss">
.msgbox {
  width: 60%;
}
</style>
