<template>
  <div class="card-container">
    <el-card class="card-heard">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" >
        <el-form-item label="订单编号" prop="id">
          <el-input
            v-model="queryParams.param.id"
            placeholder="请输入订单编号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="停车场名称" prop="parkingId">
          <el-select
            v-model="queryParams.param.parkingId"
            placeholder="请输入停车场名称"
            clearable
          >
            <el-option
              v-for="item in parkNameList"
              :key="item.id"
              :label="item.parkingName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="车位编号" prop="spaceNo">
          <el-input
            v-model="queryParams.param.spaceNo"
            placeholder="请输入车位编号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="业主手机号" prop="userPhone">
          <el-input
            v-model="queryParams.param.userPhone"
            placeholder="请输入业主手机号"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderState">
          <el-select
            v-model="queryParams.param.orderState"
            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="tenantUserId">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width: 280px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </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-card>
    <el-card class="card-body">
      <!--        <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="['order: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="['order: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="['order:remove']"
                      >删除
                      </el-button>
                  </el-col>
              </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="订单编号" align="center" prop="id" width="200" :show-overflow-tooltip="true"/>
        <el-table-column label="停车场名称" align="center" prop="parkingName" :show-overflow-tooltip="true"/>
        <el-table-column label="车位编号" align="center" prop="spaceNo" :show-overflow-tooltip="true"/>
        <el-table-column label="业主手机号" align="center" prop="userPhone" :show-overflow-tooltip="true"/>
        <el-table-column label="订单状态" align="center" prop="orderState":show-overflow-tooltip="true"/>
        <el-table-column label="起止时间" align="center" prop="leaseStart" width="280" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.leaseStart, '{y}-{m}-{d} {h}:{i}') }}</span> 至
            <span>{{ parseTime(scope.row.leaseEnd, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="支付金额" align="center" prop="payPrice" :show-overflow-tooltip="true"/>
        <el-table-column label="租客手机号" align="center" prop="phone" :show-overflow-tooltip="true"/>
        <el-table-column label="租客车牌号" align="center" prop="carNumber":show-overflow-tooltip="true"/>
<!--        <el-table-column label="租客昵称" align="center" prop="nikeName" :show-overflow-tooltip="true"/>-->
        <el-table-column label="支付方式" align="center" prop="payType":show-overflow-tooltip="true"/>
        <el-table-column label="下单时间" align="center" prop="createTime" width="200" :show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <div v-if="scope.row.orderState=='退款待审核'">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row,1)"
                v-hasPermi="['order:edit']"
              >审核
              </el-button>
            </div>
            <el-button
              size="mini"
              type="text"
              v-if="scope.row.orderState!='退款待审核' && scope.row.orderState!='拒绝退款'"
              v-hasPermi="['order:edit']"
            >--
            </el-button>
            <div v-if="scope.row.orderState=='拒绝退款'">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row,2)"
                v-hasPermi="['order:edit']"
              >查看原因
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <pagination
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @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="updateTime">
          {{form.updateTime? form.updateTime.substr(0,16):''}}
        </el-form-item>
        <el-form-item label="退款原因" prop="reason">
          {{form.reason}}
        </el-form-item>
        <el-form-item label="">
          <!-- 图片循环展示 -->
          <div class="screen-se" v-if="picList!=null && picList.length>0">
            <viewer :imglist="picList" class="screen-view">
              <img class="screen-img" :src="item" v-for="(item,index ) in picList" :key="index" style="width: 100px;height: 100px;margin-right: 10px;"/>
            </viewer>
          </div>
           <img v-else src="../../assets/image/addPicture.png" style="width: 100px;height: 100px;"/>
        </el-form-item>
        <el-form-item label="审核意见" v-if="form.orderState!='已驳回'">
        <el-radio  v-model="radio" label="1">同意</el-radio>
        <el-radio  v-model="radio" label="2">拒绝</el-radio>
        </el-form-item>
        <el-form-item label="拒绝原因"  v-if="form.orderState=='已驳回'" style="margin-top:30px" prop="rebackReason">
          {{form.rebackReason}}
        </el-form-item>
        <el-form-item label="拒绝原因"  v-if="radio=='2' && form.orderState!='已驳回'" style="margin-top:30px" prop="rebackReason">
          <el-input type="textarea" :rows="4" placeholder="请填写拒绝原因" v-model="form.rebackReason" maxlength="100">
          </el-input>
        </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>
  </div>
</template>

<script>
import {
  listParkName
} from '@/api/carManage/parking'
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  exportOrder
} from '@/api/orderManage/order'

export default {
  name: 'Order',
  components: {},
  data() {
    return {
      //图片列表
      picList: [],
      tempPic: '',
      radio: "1",
      rebackReason: "",
      openReasonFlag: false,
      // 状态数据字典
      statusOptions: [],
      // 选择停车场名称列表
      parkNameList: [],
      // 日期范围
      dateRange: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 共享车位订单表格数据
      orderList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        param: {
          sharedId: null,
          payPrice: null,
          payType: null,
          orderState: null,
          tenantUserId: null,
          tenantCarId: null,
          isDel: null,
          version: null,
          parkingId: null,
          spaceNo: null,
          userPhone: null,
          rebackReason: null
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        rebackReason: [
          { required: true, message: "拒绝原因不能为空", trigger: "blur" }
        ],
        sharedId: [
          {
            required: true,
            trigger: 'blur'
          }
        ],
        payPrice: [
          {
            required: true,
            trigger: 'blur'
          }
        ],
        tenantUserId: [
          {
            required: true,
            trigger: 'blur'
          }
        ],
        tenantCarId: [
          {
            required: true,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.initTime();
    this.getList()
    this.getDicts("order_status").then(response => {
      this.statusOptions = response.data;
      // 状态007小程序端还未开发暂时过滤掉
      this.statusOptions = this.statusOptions.filter(item=>item.dictValue!='007')
    });
    listParkName({}).then(response => {
      this.parkNameList = response.result
    })
  },
  methods: {
    initTime() {
      // 初始化查询，默认为前30天到今天
      let date = new Date();
      let startDate = new Date(date.getTime() - 24 * 60 * 60 * 1000 * 30);
      let endDate = date;
      this.dateRange = [
        this.getDateDay(startDate),
        this.getDateDay(endDate),
      ];
    },
    getDateDay(date) {
      //获取当前时间的年份转为字符串
      let year = date.getFullYear().toString(); //'2019'
      //获取月份，由于月份从0开始，此处要加1，判断是否小于10，如果是在字符串前面拼接'0'
      let month =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1).toString()
          : (date.getMonth() + 1).toString(); //'04'
      //获取天，判断是否小于10，如果是在字符串前面拼接'0'
      let da =
        date.getDate() < 10
          ? "0" + date.getDate().toString()
          : date.getDate().toString(); //'12'
      //字符串拼接，开始时间，结束时间
      return year + "-" + month + "-" + da; //当天'2019-04-12'
    },
    /** 查询共享车位订单列表 */
    getList() {
      this.loading = true
      if (null != this.dateRange && '' != this.dateRange) {
        this.queryParams.param["beginTime"] = this.dateRange[0];
        this.queryParams.param["endTime"] = this.dateRange[1];
      }
      listOrder(this.queryParams).then(response => {
        this.orderList = response.records
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sharedId: null,
        payPrice: null,
        payType: null,
        orderState: null,
        tenantUserId: null,
        tenantCarId: null,
        createTime: null,
        updateTime: null,
        remark: null,
        isDel: null,
        version: null,
        parkingId: null,
        spaceNo: null,
        userPhone: null,
        rebackReason: null
      }

      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams = {
        current: 1,
        size: 10,
        param: {},
      };
      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,type) {
      this.reset()
      const id =
        row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.result
        if (this.form.pic != null && this.form.pic != '') {
          this.tempPic = this.form.pic
          this.picList = this.form.pic.split(',')
        }
        this.open = true
        if (type == 1) {
          this.title = '审核'
        } else if (type == 2) {
          this.title = '查看原因'
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if(this.radio=="1"){
            this.form.orderState ="006";//已退款
          }else if(this.radio=="2"){
            this.form.orderState ="008";//拒绝
          }
          // 新增拒绝原因表时候用
          if(this.tempPic!=null && this.tempPic!=''){
            this.form.pic = this.tempPic
          }
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              console.log('2222',response)
              if (response.result.code == 100) {
                this.msgError(response.result.msg)
                return false
              } else if(response.code==200){
                this.msgSuccess('退款成功')
                this.open = false
                this.getList()
              }
            })
          } /*else {
            addOrder(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 delOrder(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      })
    }
  }
}
</script>
