<template>
  <div>
    <obj-modal
      ref="modal"
      labelWidth="150px"
      :modalConfig="modalConfig"
      :modalData="modalData"
      :modalHandles="modalHandles"
    >
      <div slot="dialog__content">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="150px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="定金支付时间：" prop="startTime">
                <el-date-picker
                  @change="getOrderTime"
                  format="yyyy-MM-dd HH:mm"
                  data-format="yyyy-MM-dd HH:mm"
                  popper-class="show-time-hint"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  v-model="orderTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :editable="false"
                  :picker-options="pickerOptions"
                >
                </el-date-picker> </el-form-item
            ></el-col>
            <el-col :span="12">
              <el-form-item
                label="尾款支付时间："
                prop="balancePaymentStartTime"
              >
                <el-date-picker
                  @change="getArrearsTime"
                  format="yyyy-MM-dd HH:mm"
                  data-format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  v-model="arrears"
                  popper-class="show-time-hint"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions2"
                >
                </el-date-picker> </el-form-item
            ></el-col>
          </el-row>
          <el-form-item
            label="可预约发货时间："
            prop="estimatedStartDeliveryTime"
          >
            <el-date-picker
              format="yyyy-MM-dd HH:mm"
              data-format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="deliveryTime"
              v-model="delivery"
              popper-class="show-time-hint"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions3"
            >
            </el-date-picker>
            <div style="color: red;">
              顾客支付定金时、可对此区间的日期进行预约，卖家须在顾客已选预约日进行发货
            </div>
          </el-form-item>
          <el-form-item label="定金可退：" prop="isRefundEarnestMoney">
            <el-radio v-model="ruleForm.isRefundEarnestMoney" :label="1"
              >是</el-radio
            >
            <el-radio v-model="ruleForm.isRefundEarnestMoney" :label="0"
              >否</el-radio
            >
            <span>
              选择是，用户可在付尾款前申请退定金（申请后自动退，无需审核），或付尾款时间结束后系统自动退定金
            </span>
          </el-form-item>
          <el-form-item v-if="isAdd" label="选择商品：" prop="productList">
            <el-button type="primary" @click="selectProduct"
              >点击请选择商品</el-button
            >
            <span> 备注：一次最多添加五个商品 </span>
          </el-form-item>

          <div style="padding: 0 0 0 20px; font-size: 16px; font-weight: 600">
            已选择商品
          </div>
          <div v-if="isAdd" style="padding: 20px">
            <div
              v-for="item in ruleForm.productList"
              :key="item.id"
              style="border-top: 1px solid #ccc; padding: 10px 0 0 0"
            >
              <div style="font-size: 16px; margin-bottom: 20px">
                <span>商品ID:{{ item.productId }}</span>
                <span style="margin-left: 20px">商品名称:{{ item.name }}</span>
              </div>
              <el-table
                border
                ref="multipleTable"
                :data="item.productSpecificationList"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
                <el-table-column align="center" label="是否预售" width="80">
                  <template slot-scope="scope">
                    <el-checkbox
                      :true-label="1"
                      :false-label="0"
                      v-model="scope.row.isAdvanceSell"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="SKU-ID" prop="id" />
                <el-table-column
                  align="center"
                  label="规格"
                  prop="attributeList"
                >
                  <template slot-scope="scope">
                    <span>{{ scope.row.attributeValue }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="属性" prop="address">
                  <template slot-scope="scope">
                    <span>{{
                      scope.row.attributeList
                        ? scope.row.attributeList[0].attributeName
                        : '无'
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="销售价"
                  prop="marketPrice"
                  width="120"
                />
                <el-table-column align="center" label="*是否预售" width="200">
                  <template slot="header">
                    <span style="color: red">*预售价</span>
                  </template>
                  <template slot-scope="scope">
                    <el-input-number
                      v-if="scope.row.isAdvanceSell"
                      @change="
                        scope.row.balancePayment =
                          Number(scope.row.presalePrice) &&
                          Number(scope.row.earnestMoney)
                            ? parseFloat(
                                String(
                                  scope.row.presalePrice -
                                    scope.row.earnestMoney
                                )
                              ).toFixed(2)
                            : 0
                      "
                      v-model="scope.row.presalePrice"
                      :min="0"
                      label="请输入销售价"
                    ></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="*定金" width="200">
                  <template slot="header">
                    <span style="color: red">*定金</span>
                  </template>
                  <template slot-scope="scope">
                    <el-input-number
                      @change="
                        scope.row.balancePayment =
                          Number(scope.row.presalePrice) &&
                          Number(scope.row.earnestMoney)
                            ? parseFloat(
                                String(
                                  scope.row.presalePrice -
                                    scope.row.earnestMoney
                                )
                              ).toFixed(2)
                            : 0
                      "
                      v-if="scope.row.isAdvanceSell"
                      v-model="scope.row.earnestMoney"
                      :min="0"
                      :max="scope.row.presalePrice"
                      label="请输入订金"
                    ></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="尾款" width="200">
                  <template slot-scope="scope">
                    <span v-if="scope.row.isAdvanceSell">{{
                      Number(scope.row.presalePrice) &&
                      Number(scope.row.earnestMoney)
                        ? parseFloat(
                            String(
                              scope.row.presalePrice - scope.row.earnestMoney
                            )
                          ).toFixed(2)
                        : ''
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="*预售库存" width="200">
                  <template slot="header">
                    <span style="color: red">*预售库存</span>
                  </template>
                  <template slot-scope="scope">
                    <el-input-number
                      v-if="scope.row.isAdvanceSell"
                      v-model="scope.row.advanceSellStockNum"
                      :min="0"
                      :max="999999"
                      :step="10"
                      :precision="0"
                      label="请输入预售库存"
                    ></el-input-number>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-empty
              v-show="ruleForm.productList.length == 0"
              description="请选择商品"
            ></el-empty>
          </div>
          <div v-else style="padding: 20px">
            <div style="border-top: 1px solid #ccc; padding: 10px 0 0 0">
              <div style="font-size: 16px; margin-bottom: 20px">
                <span>商品ID:{{ ruleForm.productId }}</span>
                <span style="margin-left: 20px"
                  >商品名称:{{ ruleForm.name }}</span
                >
              </div>
              <el-table
                border
                ref="multipleTable"
                :data="ruleForm.productSpecificationList"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange"
              >
                <el-table-column align="center" label="是否预售" width="80">
                  <template slot-scope="scope">
                    <el-checkbox
                      :true-label="1"
                      :false-label="0"
                      v-model="scope.row.isAdvanceSell"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="SKU-ID" prop="id" />
                <el-table-column
                  align="center"
                  label="规格"
                  prop="attributeList"
                >
                  <template slot-scope="scope">
                    <span>{{ scope.row.attributeValue }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="属性" prop="address">
                  <template slot-scope="scope">
                    <span>{{
                      scope.row.attributeList
                        ? scope.row.attributeList[0].attributeName
                        : '无'
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  label="销售价"
                  prop="marketPrice"
                  width="120"
                />
                <el-table-column align="center" label="*是否预售" width="200">
                  <template slot="header">
                    <span style="color: red">*预售价</span>
                  </template>
                  <template slot-scope="scope">
                    <el-input-number
                      v-if="scope.row.isAdvanceSell"
                      @change="
                        scope.row.balancePayment =
                          Number(scope.row.presalePrice) &&
                          Number(scope.row.earnestMoney)
                            ? parseFloat(
                                String(
                                  scope.row.presalePrice -
                                    scope.row.earnestMoney
                                )
                              ).toFixed(2)
                            : 0
                      "
                      v-model="scope.row.presalePrice"
                      :min="0"
                      :max="scope.row.marketPrice"
                      label="请输入销售价"
                    ></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="*定金" width="200">
                  <template slot="header">
                    <span style="color: red">*定金</span>
                  </template>
                  <template slot-scope="scope">
                    <el-input-number
                      @change="
                        scope.row.balancePayment =
                          Number(scope.row.presalePrice) &&
                          Number(scope.row.earnestMoney)
                            ? parseFloat(
                                String(
                                  scope.row.presalePrice -
                                    scope.row.earnestMoney
                                )
                              ).toFixed(2)
                            : 0
                      "
                      v-if="scope.row.isAdvanceSell"
                      v-model="scope.row.earnestMoney"
                      :min="0"
                      :max="scope.row.presalePrice"
                      label="请输入订金"
                    ></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="尾款" width="200">
                  <template slot-scope="scope">
                    <span v-if="scope.row.isAdvanceSell">{{
                      scope.row.presalePrice &&
                      scope.row.earnestMoney &&
                      scope.row.presalePrice > scope.row.earnestMoney
                        ? parseFloat(
                            String(
                              scope.row.presalePrice - scope.row.earnestMoney
                            )
                          ).toFixed(2)
                        : 0
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column align="center" label="*预售库存" width="200">
                  <template slot="header">
                    <span style="color: red">*预售库存</span>
                  </template>
                  <template slot-scope="scope">
                    <el-input-number
                      v-if="scope.row.isAdvanceSell"
                      v-model="scope.row.advanceSellStockNum"
                      :min="0"
                      :max="999999"
                      :step="10"
                      :precision="0"
                      label="请输入预售库存"
                    ></el-input-number>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-empty
              v-show="ruleForm.productList?.length == 0"
              description="请选择商品"
            ></el-empty>
          </div>
        </el-form>
      </div>
      <!-- 选择商品 -->
    </obj-modal>
    <commodity @getProduct="getProduct" ref="commodity"></commodity>
  </div>
</template>
<script>
import commodity from './commodity.vue'
import { debounce, cloneDeep } from 'lodash'
import dayjs from 'dayjs'
export default {
  components: { commodity },
  props: {
    marketId: {
      type: String,
      default: ''
    },
    shopId: {
      type: String,
      default: ''
    }
  },
  data() {
    var that = this
    return {
      isAdd: true,
      //表格属性
      modalConfig: {
        title: '库存预警设置',
        show: false,
        width: '1200px',
        fullscreen: true
      },
      modalData: {},
      ruleForm: {
        productList: [],
        isRefundEarnestMoney: 1 //定金可退 1是 0
      },
      pickerOptions: {
        disabledDate(time) {
          return (
            time.getTime() <=
            dayjs()
              .subtract(1, 'day')
              .valueOf()
          )
        }
      },
      orderTime: [], //订单支付时间
      arrears: [], //尾款时间
      pickerOptions2: {
        disabledDate(time) {
          let date = Date.now()
          if (that.ruleForm && that.ruleForm.startTime) {
            console.log(that.ruleForm.startTime)
            date = new Date(that.ruleForm.startTime).getTime()
          }
          return (
            time.getTime() <=
            dayjs(date)
              .subtract(1, 'day')
              .valueOf()
          )
        }
      },
      pickerOptions3: {
        disabledDate(time) {
          let date = Date.now()
          if (that.ruleForm && that.ruleForm.balancePaymentEndTime) {
            console.log(that.ruleForm.balancePaymentEndTime)
            date = new Date(that.ruleForm.balancePaymentEndTime).getTime()
          }
          return time.getTime() <= dayjs(date).valueOf()
        }
      },
      delivery: [], //发货时间
      tableData: [],
      rules: {
        startTime: [
          {
            required: true,
            message: '请选择支付时间',
            trigger: ['blur', 'change']
          }
        ],
        balancePaymentStartTime: [
          {
            required: true,
            message: '请选择尾款支付时间',
            trigger: 'change'
          }
        ],
        estimatedStartDeliveryTime: [
          {
            required: true,
            message: '请选择预计发货时间',
            trigger: 'change'
          }
        ],
        isRefundEarnestMoney: [
          {
            required: true,
            message: '请选择定金可退',
            trigger: 'change'
          }
        ],
        productList: [
          {
            required: true,
            message: '请选择预售商品',
            trigger: 'change'
          }
        ],
        presalePrice: [
          {
            required: true,
            message: '请输入预售价格',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  watch: {
    'modalConfig.show'(newVal) {
      if (newVal) {
        //关闭弹窗清空校验
        setTimeout(() => {
          this.$refs.ruleForm.resetFields()
        })
      }
    }
  },
  methods: {
    queryTableData(pageNo, pageSize) {},
    toggle(e) {
      if (this.modalConfig.show == false) {
        this.modalConfig.show = true
      } else {
        this.modalConfig.show = false
      }
      if (e) {
        this.init(cloneDeep(e))
      }
      return {
        add: () => {
          this.orderTime = []
          this.arrears = []
          this.delivery = []
          this.ruleForm = {
            startTime: '',
            endTime: '',
            balancePaymentStartTime: '',
            balancePaymentEndTime: '',
            estimatedStartDeliveryTime: '',
            estimatedEndDeliveryTime: '',
            productList: [],
            isRefundEarnestMoney: 1 //定金可退 1是 0
          }
          this.modalConfig.title = '新增预售'
          this.isAdd = true
        },
        update: () => {
          this.modalConfig.title = '编辑预售'
          this.isAdd = false
        }
      }
    },
    init(row) {
      console.log(row.startTime, row.endTime)
      this.orderTime = [row.startTime, row.endTime]
      this.arrears = [row.balancePaymentStartTime, row.balancePaymentEndTime]
      this.delivery = [
        row.estimatedStartDeliveryTime,
        row.estimatedEndDeliveryTime
      ]
      this.$set(this, 'ruleForm', {
        productId: row.id,
        advanceSellId: row.advanceSellId,
        startTime: this.orderTime[0],
        name: row.name,
        endTime: this.orderTime[1],
        balancePaymentStartTime: this.arrears[0],
        balancePaymentEndTime: this.arrears[1],
        estimatedStartDeliveryTime: this.delivery[0],
        estimatedEndDeliveryTime: this.delivery[1],
        isRefundEarnestMoney: Number(row.isRefundEarnestMoney),
        productSpecificationList: row.productSpecificationList
      })
      // (this.ruleForm = {
      //   productId: row.id,
      //   advanceSellId: row.advanceSellId,
      //   startTime: row.startTime,
      //   name: row.name,
      //   endTime: row.endTime,
      //   balancePaymentStartTime: row.balancePaymentStartTime,
      //   balancePaymentEndTime: row.balancePaymentEndTime,
      //   estimatedStartDeliveryTime: row.estimatedStartDeliveryTime,
      //   estimatedEndDeliveryTime: row.estimatedEndDeliveryTime,
      //   isRefundEarnestMoney: row.isRefundEarnestMoney,
      //   productSpecificationList: row.productSpecificationList,
      // }),
      console.log(this.ruleForm)
      console.log(this.orderTime, this.arrears, this.delivery)

      // this.ruleForm = row;
    },
    //订单支付时间
    getOrderTime(e) {
      if (e) {
        console.log(e)
        this.ruleForm.startTime = e[0]
        this.ruleForm.endTime = e[1]
      } else {
        this.ruleForm.startTime = ''
        this.ruleForm.endTime = ''
      }
    },
    //尾款支付时间
    getArrearsTime(e) {
      if (e) {
        console.log(e)
        this.ruleForm.balancePaymentStartTime = e[0]
        this.ruleForm.balancePaymentEndTime = e[1]
      } else {
        this.ruleForm.balancePaymentStartTime = ''
        this.ruleForm.balancePaymentEndTime = ''
      }
    },
    //发货时间
    deliveryTime(e) {
      if (e) {
        console.log(e)
        this.ruleForm.estimatedStartDeliveryTime = e[0]
        this.ruleForm.estimatedEndDeliveryTime = e[1]
      } else {
        this.ruleForm.estimatedStartDeliveryTime = ''
        this.ruleForm.estimatedEndDeliveryTime = ''
      }
    },
    selectProduct() {
      console.log('选择商品', this.marketId, this.shopId)
      this.$nextTick(() => {
        this.$refs.commodity.toggle().add({
          marketId: this.marketId,
          shopId: this.shopId
        })
      })
    },
    handleSelectionChange(e) {
      console.log(e)
    },
    getProduct(row) {
      this.ruleForm.productList = row.map(item => {
        return {
          productId: item.id,
          name: item.name,
          productSpecificationList: item.productSpecificationList
        }
      })
      console.log(this.ruleForm.productList, this.ruleForm.productList.length)

      console.log('获取商品')
    }
  },
  computed: {
    modalHandles() {
      return [
        {
          label: '取消',
          handle: () => {
            this.toggle()
          }
        },
        {
          label: '确认',
          type: 'primary',
          // submit: true,
          handle: () => {
            if (this.isAdd) {
              this.$refs.ruleForm.validate(valid => {
                if (valid) {
                  console.log(valid)
                  if (
                    dayjs(this.ruleForm.startTime).isAfter(
                      dayjs(this.ruleForm.balancePaymentStartTime)
                    )
                  ) {
                    this.$message.error(
                      '付尾款开始时间必须大于等于定金开始时间'
                    )
                    return
                  }
                  if (
                    dayjs(this.ruleForm.endTime).isAfter(
                      dayjs(this.ruleForm.balancePaymentEndTime)
                    )
                  ) {
                    this.$message.error(
                      '付尾款结束时间必须大于等于定金结束时间'
                    )
                    return
                  }
                  if (
                    dayjs(this.ruleForm.estimatedStartDeliveryTime).format(
                      'YYYY-MM-DD'
                    ) ===
                    dayjs(this.ruleForm.estimatedEndDeliveryTime).format(
                      'YYYY-MM-DD'
                    )
                  ) {
                    this.$message.error(
                      '可预约发货时间必须跨天'
                    )
                    return
                  }
                  if (
                    this.ruleForm.productList &&
                    this.ruleForm.productList.length === 0
                  ) {
                    this.$message.error('请选择商品')
                    return
                  }
                  let pass = true
                  let moneyPass = true
                  let count = 0
                  this.ruleForm.productList.forEach(product => {
                    if (
                      product.productSpecificationList &&
                      product.productSpecificationList.length
                    ) {
                      count =
                        count +
                        product.productSpecificationList.filter(
                          spec => spec.isAdvanceSell
                        ).length
                      product.productSpecificationList.forEach(spec => {
                        if (spec.isAdvanceSell) {
                          if (!spec.presalePrice) {
                            pass = false
                          }
                          if (!spec.earnestMoney) {
                            pass = false
                          }
                          if (!spec.advanceSellStockNum) {
                            pass = false
                          }
                          if (spec.presalePrice <= spec.earnestMoney) {
                            moneyPass = false
                          }
                        }
                      })
                    }
                  })
                  if (!count) {
                    this.$message.error('请勾选预售商品规格')
                    return
                  }
                  if (!pass) {
                    this.$message.error('请填写预售价、定金、预售库存')
                    return
                  }
                  if (!moneyPass) {
                    this.$message.error('定金必须小于预售价')
                    return
                  }
                  this.$api.preSale
                    .addPreSaleProducts(this.ruleForm)
                    .then(res => {
                      this.$emit('queryList')
                      this.toggle()
                    })
                }
              })
            } else {
              this.$refs.ruleForm.validate(valid => {
                if (valid) {
                  if (
                    dayjs(this.ruleForm.startTime).isAfter(
                      dayjs(this.ruleForm.balancePaymentStartTime)
                    )
                  ) {
                    this.$message.error(
                      '付尾款开始时间必须大于等于定金开始时间'
                    )
                    return
                  }
                  if (
                    dayjs(this.ruleForm.endTime).isAfter(
                      dayjs(this.ruleForm.balancePaymentEndTime)
                    )
                  ) {
                    this.$message.error(
                      '付尾款结束时间必须大于等于定金结束时间'
                    )
                    return
                  }
                  console.log(valid)
                  if (
                    this.ruleForm.productSpecificationList &&
                    this.ruleForm.productSpecificationList.length === 0
                  ) {
                    this.$message.error('请勾选商品规格')
                    return
                  }
                  let pass = true
                  let moneyPass = true
                  let count = this.ruleForm.productSpecificationList.filter(
                    spec => spec.isAdvanceSell
                  ).length
                  this.ruleForm.productSpecificationList.forEach(spec => {
                    if (spec.isAdvanceSell) {
                      if (!spec.presalePrice) {
                        pass = false
                      }
                      if (!spec.earnestMoney) {
                        pass = false
                      }
                      if (!spec.advanceSellStockNum) {
                        pass = false
                      }
                      if (spec.presalePrice <= spec.earnestMoney) {
                        moneyPass = false
                      }
                    }
                  })
                  if (!count) {
                    this.$message.error('请勾选预售商品规格')
                    return
                  }
                  if (!pass) {
                    this.$message.error('请填写预售价、定金、预售库存')
                    return
                  }
                  if (!moneyPass) {
                    this.$message.error('定金必须小于预售价')
                    return
                  }
                  this.$api.preSale
                    .updatePreSaleProducts(this.ruleForm)
                    .then(res => {
                      this.$emit('queryList')
                      this.toggle()
                    })
                }
              })
            }
          }
        }
      ]
    }
  },
  asyncComputed: {}
}
</script>
<style lang="scss">
.show-time-hint {
  .el-time-spinner {
    position: relative;
    &::before {
      content: '小时';
      display: block;
      color: black;
      position: absolute;
      top: 0;
      left: 0;
      text-align: center;
      width: 50%;
      height: 40px;
      line-height: 40px;
      font-size: 14px;
      background: white;
      z-index: 100;
    }
    &::after {
      content: '分钟';
      display: block;
      color: black;
      position: absolute;
      text-align: center;
      top: 0;
      height: 40px;
      line-height: 40px;
      right: 0;
      width: 50%;
      font-size: 14px;
      background: white;
      z-index: 100;
    }
  }
}
</style>
