<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item :label="$t('dingdanorder.订单号')" prop="ddId">
        <el-input
          v-model="queryParams.ddId"
          :placeholder="$t('dingdanorder.请输入订单号')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item :label="$t('dingdanorder.订单分类')" prop="type">-->
<!--        <el-select v-model="queryParams.type" :placeholder="$t('dingdanorder.请选择订单分类')" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in dict.type.pos_order_category"-->
<!--            :key="dict.value"-->
<!--            :label="generateTitle(dict.label)"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item :label="$t('dingdanorder.用户Id')" prop="userId">
        <el-input
          v-model="queryParams.userId"
          :placeholder="$t('dingdanorder.请输入用户Id')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="$t('dingdanorder.订单状态')" prop="state">
        <el-select v-model="queryParams.state" :placeholder="$t('dingdanorder.请选择订单状态')" clearable>
          <el-option
            v-for="dict in dict.type.sys_order_type"
            :key="dict.value"
            :label="generateTitle(dict.label)"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('dingdanorder.订单类型')" prop="type">
        <el-select v-model="queryParams.type" :placeholder="$t('dingdanorder.请选择订单类型')" clearable>
          <el-option
            v-for="dict in dict.type.sys_order_leixing"
            :key="dict.value"
            :label="generateTitle(dict.label)"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('dingdanorder.创建时间')">
        <el-date-picker
          v-model="queryParams.dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          :start-placeholder="$t('dingdanorder.开始日期')"
          :end-placeholder="$t('dingdanorder.结束日期')"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('dingdanorder.搜索')}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('dingdanorder.重置')}}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:order:edit']"
        >{{$t('dingdanorder.修改')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:order:export']"
        >{{$t('dingdanorder.导出')}}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>

      <el-table-column :label="$t('dingdanorder.订单号')" align="center" prop="ddId">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="dingdanxq(scope.row)"
          >{{scope.row.ddId}}</el-button>
        </template>
      </el-table-column>
      <el-table-column :label="$t('dingdanorder.创建时间')" align="center" prop="cretim" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.cretim, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('dingdanorder.订单金额')" align="center" prop="amount" />
      <el-table-column :label="$t('dingdanorder.商品价格')" align="center" prop="priceAll" />
<!--      <el-table-column :label="$t('dingdanorder.促销活动名称')" align="center" prop="salesName" />-->
<!--      <el-table-column :label="$t('dingdanorder.减免值')" align="center" prop="salesReduction" />-->
      <el-table-column :label="$t('dingdanorder.配送费')" align="center" prop="freight" />
      <el-table-column :label="$t('dingdanorder.配送距离')" align="center" prop="jvli" />
      <el-table-column :label="$t('dingdanorder.订单状态')" align="center" prop="state">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state==0" type="info">{{generateTitle('未支付')}}</el-tag>
          <el-tag v-if="scope.row.state==1" type="info">{{generateTitle('已付款')}}</el-tag>
          <el-tag v-if="scope.row.state==2" type="info">{{generateTitle('已接单')}}</el-tag>
          <el-tag v-if="scope.row.state==3" type="info">{{generateTitle('取餐中')}}</el-tag>
          <el-tag v-if="scope.row.state==4" type="info">{{generateTitle('配送中')}}</el-tag>
          <el-tag v-if="scope.row.state==5" type="info">{{generateTitle('已完成')}}</el-tag>
          <el-tag v-if="scope.row.state==6" type="info">{{generateTitle('申请退款')}}</el-tag>
          <el-tag v-if="scope.row.state==7" type="info">{{generateTitle('同意退款')}}</el-tag>
          <el-tag v-if="scope.row.state==8" type="info">{{generateTitle('拒绝退款')}}</el-tag>
          <el-tag v-if="scope.row.state==9" type="info">{{generateTitle('客服接入')}}</el-tag>
          <el-tag v-if="scope.row.state==10" type="info">{{generateTitle('作废')}}</el-tag>
          <el-tag v-if="scope.row.state==11" type="info">{{generateTitle('售后完成')}}</el-tag>
          <el-tag v-if="scope.row.state==12" type="info">{{generateTitle('送达')}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('dingdanorder.订单类型')" align="center" prop="type">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.type==0" >{{generateTitle('外送')}}</el-tag>
          <el-tag v-if="scope.row.type==1" type="success">{{generateTitle('自取')}}</el-tag>
          <el-tag v-if="scope.row.type==2" type="danger">{{generateTitle('堂食')}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('dingdanorder.操作')" 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="['system:order:edit']"
          >{{$t('dingdanorder.修改')}}</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:order:remove']"
          >删除</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"
    />

    <!-- 添加或修改posorder对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :label-width="$t('message.language')=='语言'?'80px':$t('message.language')=='language'?'165px':'165px'">
        <el-form-item :label="$t('dingdanorder.订单状态')" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio
              v-for="dict in dict.type.sys_order_type"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{generateTitle(dict.label)}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('dingdanorder.确定')}}</el-button>
        <el-button @click="cancel">{{$t('dingdanorder.取消')}}</el-button>
      </div>
    </el-dialog>
    <!-- 查看订单 详情 -->
    <el-dialog :title="$t('dingdanorder.订单号')+':'+orxiangq.ddId" :visible.sync="xqlan" :width="$t('message.language')=='语言'?'800px':$t('message.language')=='language'?'1000px':'1000px'" append-to-body v-loading="loding">
      <el-steps class="dibujvli" :active="orxiangq.state" finish-status="success">
        <el-step :title="$t('route.未支付')"></el-step>
        <el-step :title="$t('route.已付款')"></el-step>
        <el-step :title="$t('route.已接单')"></el-step>
        <el-step :title="$t('route.取餐中')"></el-step>
        <el-step :title="$t('route.配送中')"></el-step>
        <el-step :title="$t('route.已完成')"></el-step>
        <el-step :title="$t('route.异常')"></el-step>
      </el-steps>

     <div class="dibujvli">
        <h3>{{$t('dingdanorder.出货门店')}}</h3>
        <div class="hengxlan">
           <image-preview :src="store.image" width="80px" height="80px"/>
           <div class="jiange">
             <div class="minz">{{store.posName}}</div>
             <div>{{$t('dingdanorder.店面地址')}}:{{store.area}}{{store.address}}</div>
             <div>{{$t('dingdanorder.配送距离')}}:{{orxiangq.jvli}}km,{{$t('dingdanorder.配送费')}}:{{orxiangq.freight}}</div>
           </div>
        </div>
      </div>
     <div class="hxlan">
        <div class="youjg">
          <div>{{$t('dingdanorder.订单用户')}}</div>
          <div class="hengxlan">
            <image-preview :src="dduser.avatar" width="50px" height="50px"/>
            <div class="jiange">
              <div :class="dduser.vip==null||dduser.vip==undefined?'minz':'minz hs'">{{dduser.nickName}}</div>
              <div>{{dduser.phone}}</div>
            </div>
          </div>
        </div>
       <div class="youjg">
          <div>{{$t('dingdanorder.订单商家')}}</div>
          <div class="hengxlan">
            <image-preview :src="shus.avatar" width="50px" height="50px"/>
            <div class="jiange">
              <div class="minz">{{shus.nickName}}</div>
              <div>{{shus.phone}}</div>
            </div>
          </div>
        </div>
       <div class="youjg">
          <div>{{$t('dingdanorder.配送骑手')}}</div>
          <div class="hengxlan">
            <image-preview :src="qisus.avatar" width="50px" height="50px"/>
            <div class="jiange">
              <div class="minz">{{qisus.nickName}}</div>
              <div>{{qisus.phone}}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="dingbu">
        <div class="hengxlan">
          <h3 class="texjc youjg">{{$t('dingdanorder.订单金额')}}:{{format(orxiangq.amount)}}</h3>
          <h3 class="texjc youjg">{{$t('dingdanorder.预约配送时间')}}:{{orxiangq.delryTime||'————'}}</h3>
          <h3 class="texjc">{{orxiangq.type==2?generateTitle('堂食'):orxiangq.type==1?generateTitle('自取'):generateTitle('外送')}}</h3>
        </div>
        <!-- 新增：促销活动信息 -->
        <div style="margin: 10px 0; padding: 10px; background: #fff7e6; border-radius: 6px;">
          <div style="font-weight: bold; color: #ff5500; margin-bottom: 5px;">{{$t("dingdanorder.促销活动信息")}}</div>
          <div v-if="orxiangq.salesName || orxiangq.mdSalesName">
            <div v-if="orxiangq.salesName">
              {{$t("dingdanorder.平台促销活动")}}：{{ orxiangq.salesName }}
              <span v-if="orxiangq.salesReduction">（{{$t("dingdanorder.减免")}}：{{ orxiangq.salesReduction }}）</span>
            </div>
            <div v-if="orxiangq.mdSalesName">
              {{$t("dingdanorder.商家促销活动")}}：{{ orxiangq.mdSalesName }}
              <span v-if="orxiangq.mdSalesReduction">（{{$t("dingdanorder.减免")}}：{{ orxiangq.mdSalesReduction }}）</span>
            </div>
          </div>
          <div v-else>{{$t("dingdanorder.无")}}</div>
        </div>
        <!-- 新增：优惠券信息 -->
        <div style="margin: 10px 0; padding: 10px; background: #e6f7ff; border-radius: 6px;">
          <div style="font-weight: bold; color: #1890ff; margin-bottom: 5px;">{{$t("dingdanorder.优惠券信息")}}</div>
          <div v-if="orxiangq.yhName || orxiangq.mdYhName">
            <div v-if="orxiangq.yhName">
              {{$t("dingdanorder.平台优惠券")}}：{{ orxiangq.yhName }}
              <span v-if="orxiangq.discountAmount">（{{$t("dingdanorder.优惠金额")}}：{{ orxiangq.discountAmount }}）</span>
            </div>
            <div v-if="orxiangq.mdYhName">
              {{$t("dingdanorder.商家优惠券")}}：{{ orxiangq.mdYhName }}
              <span v-if="orxiangq.mdDiscountAmount">（{{$t("dingdanorder.优惠金额")}}：{{ orxiangq.mdDiscountAmount }}）</span>
            </div>
          </div>
          <div v-else>{{$t("dingdanorder.无")}}</div>
        </div>
        <!-- 新增：积分使用情况 -->
        <div style="margin: 10px 0; padding: 10px; background: #f3e6ff; border-radius: 6px;">
          <div style="font-weight: bold; color: #722ed1; margin-bottom: 5px;">{{$t("dingdanorder.积分使用情况")}}</div>
          <div v-if="orxiangq.points && orxiangq.pointsReduction">
            <div>
              {{$t("dingdanorder.使用积分数量")}}：{{ orxiangq.points }}
              <span v-if="orxiangq.pointsReduction">（{{$t("dingdanorder.抵扣金额")}}：{{ orxiangq.pointsReduction }}）</span>
            </div>
          </div>
          <div v-else>{{$t("dingdanorder.无")}}</div>
        </div>
        <div class="dibujvli" v-if="useradd">
          <div class="hengxlan texjc xias">
            <div>{{$t('dingdanorder.收货人')}}:{{useradd.name}}</div>
            <div class="jiange">{{$t('dingdanorder.联系电话')}}:{{useradd.phone}}</div>
          </div>
          <div>
            <div>{{$t('dingdanorder.地区')}}:{{useradd.country}}{{useradd.city}}{{useradd.area}}</div>
            <div>{{$t('dingdanorder.收货地址')}}:{{useradd.address}}</div>
          </div>
        </div>
        <div style="margin-bottom: 30px;">
          <div style="font-weight: bold;margin-bottom: 10px;">{{$t('dingdanorder.备注')}}</div>
          <div>{{orxiangq.remarks}}</div>
        </div>
        <div>
          <div class="hengxlan dibujvli" v-for="item in food">
             <image-preview :src="item.image" width="70px" height="70px"/>
             <div class="jiange">
               <div class="texjc">{{item.name}}</div>
               <div>{{$t('dingdanorder.价格')}}:{{format(item.price+item.otherPrice)}} |  {{$t('dingdanorder.数量')}}:{{item.number}} |  {{$t('dingdanorder.小计')}}:{{format(item.number*(item.price+item.otherPrice))}}</div>
               <div class="hengxlan">
                 <div>{{$t('dingdanorder.规格')}}:</div>
                 <div v-if="item.ask.length==0">--</div>
                 <div class="guige" v-for="em in item.ask">{{em}}</div>
               </div>
               <div>{{$t('dingdanorder.备注')}}:{{item.beizhu}}</div>
             </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button  type="primary" @click="guanbi">{{$t('dingdanorder.关闭')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder,getvip,getorderhout } from "@/api/system/order";
import {generateTitle} from '../../../utils/i18.js'
export default {
  name: "Order",
  dicts: ['sys_order_leixing', 'sys_order_type'],
  data() {
    return {
      loding:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // posorder表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      xqlan:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 日期范围
        dateRange: "",
        ddId: null,
        shId: null,
        mdId: null,
        cretim: null,
        shdzId: null,
        userId: null,
        amount: null,
        state: null,
        type: null,
        delryTime: null
      },
      // 表单参数
      form: {},
      orxiangq:{}, //订单详请
      store:{},
      dduser:{},
      shus:{},
      qisus:{},
      useradd:null,
      food:[],
      // 表单校验
      rules: {

      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    generateTitle,
    guanbi(){
      this.xqlan =false
    },
    format(str) {
      var arr = [];
        var counter = 0;
        str = (str || 0).toString().split("");
        for (var i = str.length - 1; i >= 0; i--) {
          counter++;
          arr.unshift(str[i]);
          if (!(counter % 3) && i !== 0) {
            arr.unshift(",");
          }
        }
        return arr.join("");
    },

    /** 查询posorder列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        var list = response.rows;
        for(let i=0;i<list.length;i++){
          list[i].amount = this.format(list[i].amount);
          list[i].freight = this.format(list[i].freight);
          list[i].priceAll = this.format(list[i].priceAll);
        }
        this.orderList = list;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        ddId: null,
        shId: null,
        mdId: null,
        cretim: null,
        shdzId: null,
        userId: null,
        amount: null,
        remarks: null,
        state: null,
        type: null,
        delryTime: null,
        logo: null,
        posName: 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 = "添加posorder";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('dingdanorder.修改订单状态');
      });
    },
    // 查看订单详请
    dingdanxq(row){

      this.loding = true;
      getorderhout(row.id).then(response => {
        console.log("订单信息",response.data);
        this.orxiangq = response.data;
        this.store = response.data.store==null?{}:response.data.store;
        this.dduser = response.data.user==null?{}:response.data.user;
        this.shus = response.data.shanghu==null?{}:response.data.shanghu;
        this.qisus = response.data.qsuser==null?{}:response.data.qsuser;
        this.food = response.data.food==null?[]:response.data.food;
        this.useradd = response.data.shaddress;
        this.loding = false;
        this.xqlan = true;
        getvip(response.data.user.userId).then(res=>{
          this.dduser.vip = res.data;
           console.log("会员信息",res.data);

        })

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('dingdanorder.修改成功'));
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('dingdanorder.新增成功'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除posorder编号为"' + ids + '"的数据项？').then(function() {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
  .dingbu{
    margin-top: 20px;
  }
  .dibujvli{
    margin-bottom: 20px;
  }
  .xias{
    margin-bottom: 10px;
  }
  .hxlan{
    display: flex;
    align-items: center;
  }
  .youjg{
    margin-right: 40px;
  }
  .guige{
    padding: 3px 10px;
    background-color: #ff557f;
    color: #ffffff;
    border-radius: 8px;
    margin-right: 10px;
  }
  .hengxlan{
    display: flex;
    align-items: center;
    margin-top: 10px;
  }
  .jiange{
    margin-left: 10px;
  }
  .texjc{
    font-weight: bold;
  }
  .hs{
    color: #ff5500;
  }
  .minz{
    font-size: 15px;
    font-weight: bold;
    margin-bottom: 10px;
  }
</style>
