<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <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="createAt">
        <el-input
          v-model="queryParams.createAt"
          placeholder="请输入下单时间"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall:mallOrderOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mall:mallOrderOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mall:mallOrderOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['mall:mallOrderOrder:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          @click="editPostForm()"
        >配送设置</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mallOrderOrderList"  @selection-change="handleSelectionChange" :summary-method="getSummaries" show-summary>
      <el-table-column type="selection" width="55" align="center" />
      <!--<el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="订单原价" align="center" prop="orderPrice" />
      <el-table-column label="实付金额" align="center" prop="payment" />
      <el-table-column label="邮费" align="center" prop="postFee" />
      <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="createAt" />
      <el-table-column label="支付时间" align="center" prop="payAt" />
      <el-table-column label="支付类型" align="center" prop="payType" />
      <el-table-column label="买家留言" align="center" prop="buyerMsg" />
      <!--<el-table-column label="是否申请退款" align="center" prop="isRefund" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mall:mallOrderOrder:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mall:mallOrderOrder:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleChackDetail(scope.row)"
            v-hasPermi="['mall:mallOrderOrder:chackDetail']"
          >查看详情</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="订单状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="快递公司代号" prop="shippingMark">
          <el-input v-model="form.shippingMark" placeholder="请输入快递公司代号" />
        </el-form-item>
        <el-form-item label="物流名称" prop="shippingName">
          <el-input v-model="form.shippingName" placeholder="请输入物流名称" />
        </el-form-item>
        <el-form-item label="物流单号" prop="shippingCode">
          <el-input v-model="form.shippingCode" placeholder="请输入物流单号" />
        </el-form-item>
        <!--<el-form-item label="是否申请退款" prop="isRefund">-->
          <!--<el-input v-model="form.isRefund" placeholder="请输入是否申请退款0=不是,1=是" />-->
        <!--</el-form-item>-->
        <el-form-item label="收件人" prop="receiverName">
          <el-input v-model="form.receiverName" placeholder="请输入收件人" />
        </el-form-item>
        <el-form-item label="电话" prop="receiverPhone">
          <el-input v-model="form.receiverPhone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="省份" prop="receiverProvince">
          <el-input v-model="form.receiverProvince" placeholder="请输入省份" />
        </el-form-item>
        <el-form-item label="城市" prop="receiverCity">
          <el-input v-model="form.receiverCity" placeholder="请输入城市" />
        </el-form-item>
        <el-form-item label="区县" prop="receiverArea">
          <el-input v-model="form.receiverArea" placeholder="请输入区县" />
        </el-form-item>
        <el-form-item label="地址" prop="receiverAddress">
          <el-input v-model="form.receiverAddress" 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-dialog title="配送设置" :visible.sync="postOpen" width="500px" append-to-body>
      <el-form ref="postForm" :model="postForm" :rules="postFormRules" label-width="80px">
        <el-form-item label="金额" prop="price">
          <el-input-number v-model="postForm.price" :precision="2" :step="0.1" :min="0" placeholder="请输入金额"/>
        </el-form-item>
        <el-form-item label="邮费" prop="postFee">
          <el-input-number v-model="postForm.postFee" :precision="2" :step="0.1" :min="0" placeholder="请输入邮费"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPostForm">确 定</el-button>
        <el-button @click="cancelPostForm">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog  :visible.sync="menuRoleVisible" append-to-body>
      <order-goods v-if="menuRoleVisible" ref="OrderGoods"></order-goods>
    </el-dialog>
  </div>
</template>

<script>
import { listMallOrderOrder, getMallOrderOrder, delMallOrderOrder, addMallOrderOrder, updateMallOrderOrder, exportMallOrderOrder } from "@/api/mall/mallOrderOrder";
import { selectMallOrderPostById, editMallOrderPost } from "@/api/mall/mallOrderPost";
import OrderGoods from "../mallOrderGoods/index";

export default {
  name: "MallOrderOrder",

  components:{
    OrderGoods
  },

  data() {
    return {
      menuRoleVisible : false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      mallOrderOrderList: [],
      statusOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: null,
        createAt: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderNo: [
          { required: true, message: "订单号不能为空", trigger: "blur" }
        ],
        payment: [
          { required: true, message: "实付金额不能为空", trigger: "blur" }
        ],
      },
      postForm:{},
      postFormRules:{
      },
      postOpen: false
    };
  },

  created() {
    this.getList();
    this.getDicts("mall_order_status").then(response => {
      this.statusOptions = response.data;
  });
  },
  methods: {
    editPostForm(){
      this.postForm = {
        orderPostId: 0.00,
        price: 0.00,
        postFee: 0.00
      };
      selectMallOrderPostById().then(res =>{
        this.postForm = res.data;
      })
      this.postOpen = true;
    },
    submitPostForm(){

      this.$refs["postForm"].validate(valid => {
        if (valid) {
          editMallOrderPost(this.postForm).then(res =>{
            this.msgSuccess("修改成功");
            this.postOpen = false;
          })
        }
      });
    },
    cancelPostForm(){
      this.postForm = {
        orderPostId: 0.00,
        price: 0.00,
        postFee: 0.00
      };
      this.postOpen = false;

    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listMallOrderOrder(this.queryParams).then(response => {
        this.mallOrderOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }

        const values = data.map(item => Number(item[column.property]));
        console.log(column.property);
        if (!values.every(value => isNaN(value)) && ("payment" == column.property || "orderPrice" == column.property)) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        } else {
          sums[index] = '';
        }
      });

      return sums;
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderNo: null,
        userId: null,
        postFee: null,
        orderPrice: null,
        payment: null,
        status: "0",
        createAt: null,
        payAt: null,
        payType: null,
        consignAt: null,
        enterAt: null,
        returnAt: null,
        completeAt: null,
        shippingMark: null,
        shippingName: null,
        shippingCode: null,
        buyerMsg: null,
        isRefund: null,
        receiverName: null,
        receiverPhone: null,
        receiverProvince: null,
        receiverCity: null,
        receiverArea: null,
        receiverAddress: null,
        year: null,
        month: null,
        day: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMallOrderOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    handleChackDetail(row){
      let orderId = row.id;
      this.menuRoleVisible = true;
      this.$nextTick(()=>{
        this.$refs.OrderGoods.getInit(orderId);
    })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMallOrderOrder(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMallOrderOrder(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除订单编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMallOrderOrder(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有订单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportMallOrderOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
