<template>
  <div class="app-container">
    <div v-if="editType === 'add'" class="filter-container">
      <div class="filter-control">
        <span style="color: red;">在本页面，对每三个月给超级会员自动发放的优惠券进行配置，配置完成后下一阶段才生效（最少配置1个，最多5个）。</span>
        <el-button type="primary" icon="el-icon-plus" size="mini" :disabled="disabled" @click="handleAddList">新增优惠券</el-button>
      </div>
    </div>
    <div v-else class="filter-container">
      <div class="filter-control">
        <span>优惠月份:</span>
        <el-input
          v-model="formParams.month"
          placeholder="开始月份"
          clearable
          suffix-icon="el-icon-date"
          :disabled="true"
          style="width:100px;"
        />
        -
        <el-input
          v-model="formParams.endMonth"
          placeholder="结束月份"
          clearable
          suffix-icon="el-icon-date"
          :disabled="true"
          style="width:100px;"
        />
        <el-button type="primary" icon="el-icon-plus" size="mini" :disabled="disabled" style="margin-left: 30px;" @click="handleAddList">新增优惠券</el-button>
      </div>
    </div>
    <el-form ref="couponFrom" :model="form" label-width="100px">
      <div v-for="(formItem,index) in form.formList" :key="formItem.key" class="form-cell" :data-key="formItem.key">
        <el-form-item :label="`优惠券${index+1}:`" style="margin-bottom: 10px;" :rules="rules.couponType">
          <el-radio-group v-model="formItem.couponType">
            <el-radio :label="0">活动券</el-radio>
            <el-radio :label="1">品类券</el-radio>
            <el-radio :label="3">店铺券</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="formItem.couponType === 3">
          <el-form-item label="供应商" :prop="`formList.${index}.shopData`" :rules="rules.shopData">
            <template v-if="formItem.shopData && formItem.shopData.length === 0">
              <el-button type="primary" autofocussize="mini" size="mini" icon="el-icon-plus" @click="handleShopDialogVisible(index)">选择供应商</el-button>
              <el-checkbox-group v-show="false" v-model="formItem.shopData" />
            </template>
            <template v-else>
              <el-table :data="formItem.shopData" border width="1000">
                <el-table-column prop="name" label="供应商名称" align="center" width="300" />
                <el-table-column prop="sname" label="供应商简称" align="center" width="200" />
                <el-table-column prop="linkMan" label="联系人" align="center" width="100" />
                <el-table-column prop="contractMobile" label="手机号" align="center" width="150">
                  <template slot-scope="{ row }">
                    {{ row.contractMobile ? row.contractMobile : '---' }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <el-button type="text" @click="deleteShop(formItem,index)">删除</el-button>
                </el-table-column>
              </el-table>
            </template>
          </el-form-item>
        </template>
        <el-form-item label="优惠券金额:" :prop="`formList.${index}.couponAmount`" :rules="rules.couponAmount">
          <el-input v-model="formItem.couponAmount" style="width: 150px" size="mini" />
        </el-form-item>
        <el-form-item label="优惠条件:" :prop="`formList.${index}.touchPrice`" :rules="rules.touchPrice">
          <el-input v-model="formItem.touchPrice" style="width: 220px" size="mini">
            <template slot="prepend" style="padding: 0 10px;">订单商品总额满：</template>
          </el-input>
        </el-form-item>
        <el-form-item label="优惠商品:" :hidden="formItem.couponType === 0 ? false : true" style="margin-bottom: 10px;" :rules="rules.productType">
          <el-radio-group v-model="formItem.productType">
            <el-radio :label="'1'">全商城商品</el-radio>
            <el-radio :label="'2'">指定商品</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="formItem.productType === '2'&& formItem.couponType === 0">
          <el-form-item label="商品信息" :prop="`formList.${index}.associateList`" :rules="rules.associateList">
            <el-button type="primary" icon="el-icon-sort" size="mini" :disabled="disabled3(formItem.associateList)" @click="handleOnInputBlur(formItem,index)">一键排序</el-button>
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleGoodDialogVisible(index)">添加商品</el-button>
            <el-checkbox-group v-show="false" v-model="formItem.associateList" />
            <el-table v-show="formItem.associateList && formItem.associateList.length>0" :data="formItem.associateList" border>
              <el-table-column property="mainImage" label="商品图片" align="center" width="80">
                <template slot-scope="{ row }">
                  <el-popover
                    placement="top-start"
                    title=""
                    width="180"
                    trigger="hover"
                  >
                    <img :src="row.mainImage" alt="" style="width:150px;height:150px;">
                    <img slot="reference" :src="row.mainImage" alt="" style="width:30px;height:30px;">
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column property="name" label="商品名称" align="center" />
              <el-table-column property="shopName" label="供应商" align="center" />
              <el-table-column label="网站状态" align="center" width="80">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.pcStatus"
                    active-color="#1890ff"
                    inactive-color="#DCDFE6"
                    active-value="1"
                    inactive-value="0"
                  />
                </template>
              </el-table-column>
              <el-table-column label="小程序状态" align="center" width="100">
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.appletsStatus"
                    active-color="#1890ff"
                    inactive-color="#DCDFE6"
                    active-value="1"
                    inactive-value="0"
                  />
                </template>
              </el-table-column>
              <el-table-column label="排序" align="center" width="100">
                <template slot-scope="{row}">
                  <el-input v-model="row.sort" maxlength="4" minlength="1" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleDeletePros(formItem,scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </template>
        <el-form-item label="优惠品类:" :hidden="formItem.couponType ===1 ? false : true" :rules="rules.categoryType">
          <el-radio-group v-model="formItem.categoryType">
            <el-radio :label="'1'">产品</el-radio>
            <el-radio :label="'2'">仪器</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-button class="delete_label" :disabled="disabled1" icon="el-icon-delete" size="mini" type="danger" @click="handleDelete(formItem,index)">删除</el-button>
      </div>
    </el-form>
    <div class="el-dialog__footer">
      <el-button type="primary" @click="onSubmit('couponFrom')">保存</el-button>
    </div>
    <!-- 供应商弹框 -->
    <shop-dialog v-if="dialogShopVisible" ref="shopDialog" @cancel="handleShopCancel" @confirm="handleShopConfirm" />
    <!-- 商品弹框 -->
    <good-dialog v-if="dialogGoodVisible" ref="goodDialog" @cancel="handleGoodCancel" @confirm="handleGoodConfirm" />
  </div>
</template>

<script>
import { svipCoupon, saveVipCoupon, delCoupon } from '@/api/member/member'
import goodDialog from './components/good-dialog'
import shopDialog from './components/shop-dialog'
const defaultForm = () => {
  return {
    shopId: 0,
    shopData: [],
    couponType: 0,
    couponAmount: '',
    touchPrice: '',
    productType: '1',
    categoryType: '1',
    associateList: []// 指定商品信息
  }
}
export default {
  name: 'MemberEdit',
  components: { goodDialog, shopDialog },
  data() {
    return {
      defaultShop: {
        shopId: 0,
        shopData: []
      },
      form: {
        formList: []
      },
      formParams: {
        id: '',
        month: '',
        endMonth: '',
        status: '',
        configure: 1, // 专属优惠券配置  1是、0否
        coupons: []
      },
      doctorId: '',
      editType: 'add',
      time: '',
      dialogTableVisible: false,
      shopTotal: 0,
      rows: [],
      // 供应商列表
      shopTableData: [],
      // 商品列表
      dialogProductVisible: false,
      productTableData: [],
      productTotal: 0,
      addIndex: 0,
      dialogShopVisible: false,
      dialogGoodVisible: false,
      rules: {
        couponType: [{ required: true, message: '请选择优惠券类型', trigger: 'blur' }],
        shopId: [{ required: true, message: '请选择供应商', trigger: 'blur' }],
        productType: [{ required: true, message: '请选择优惠商品', trigger: 'blur' }],
        shopData: [{ required: true, type: 'array', message: '请添加一个供应商', trigger: ['change'] }],
        associateList: [{ required: true, type: 'array', message: '请至少添加一个商品', trigger: ['change'] }],
        categoryType: [{ required: true, message: '请选择优惠品类', trigger: 'blur' }],
        couponAmount: [{ required: true, message: '优惠券金额不能为空', trigger: 'blur' }],
        touchPrice: [{ required: true, message: '优惠条件不能为空', trigger: 'blur' }]
      },
      delFlag: false
    }
  },
  computed: {
    disabled() {
      return this.form.formList.length === 5
    },
    disabled1() {
      return this.form.formList.length === 1
    }
  },
  created() {
    this.editType = this.$route.query.type || 'edit'
    console.log('editType', this.editType)
    this.initForm(this.editType)
  },
  methods: {
    initForm(type) {
      if (type === 'add') {
        console.log('add')
        this.svipCoupon(type, 1, 0)
      } else {
        console.log('edit')
        this.svipCoupon(type, 0, this.$route.query.id)
      }
    },
    async svipCoupon(type, configure, id) {
      const res = await svipCoupon({ id: id, configure: configure })
      const data = res.data.svipcouponForm
      this.formParams = { ...this.formParams, ...data }
      if (data.coupons.length > 0) {
        this.delFlag = true
        this.form.formList = data.coupons.map((el) => {
          el = { ...el, ...this.defaultShop }
          if (el.shop) {
            el.shopData.push(el.shop)
          }
          return el
        })
        console.log('formList', this.form.formList)
      } else {
        for (let i = 0; i <= 2; i++) {
          this.form.formList.push(defaultForm())
        }
      }
    },
    handleShopDialogVisible(index) {
      // 显示选择供应商弹窗
      this.addIndex = index
      this.dialogShopVisible = true
    },
    handleGoodDialogVisible(index) {
      // 显示选择商品弹窗
      this.addIndex = index
      this.dialogGoodVisible = true
    },

    deleteShop(formItem, index) {
      // 清除供应商
      formItem.shopId = ''
      formItem.shopData = []
      this.$nextTick(() => {
        console.log('index', formItem)
        this.form.formList[index].shopId
        this.form.formList[index].shopData
      })
    },
    handleShopConfirm(data) {
      // 确认选择供应商
      this.form.formList[this.addIndex].shopId = data.shopId
      this.form.formList[this.addIndex].shopData.push(data)
      console.log('formList', this.form.formList[this.addIndex])
      this.handleShopCancel()
    },
    handleGoodConfirm(data) {
      // 确认选择商品
      console.log('data', data)
      console.log('addIndex', this.addIndex)
      const from = this.form.formList[this.addIndex]
      from.associateList.push(data)
      console.log('from', this.form.formList)
      this.handleGoodCancel()
    },
    handleDeletePros(formItem, index) {
      // 删除商品
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        formItem.associateList.splice(index, 1)
      })
    },
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleFormParams()
          this.$confirm('是否提交数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log('formParams', this.formParams)
            if (this.editType === 'add') {
              this.formParams.configure = 1
            } else {
              this.formParams.configure = 0
            }
            this.saveVipCoupon(this.formParams)
          })
        } else {
          return false
        }
      })
    },
    handleFormParams() {
      // 处理参数
      this.formParams.coupons = this.form.formList.map((el) => {
        if (el.associateList && el.associateList.length > 0) {
          el.associateList = el.associateList.map((pro) => {
            return {
              sort: pro.sort,
              pcStatus: pro.pcStatus,
              appletsStatus: pro.appletsStatus,
              name: pro.name,
              shopName: pro.shopName,
              mainImage: pro.mainImage,
              productId: pro.productId
            }
          })
        }
        return el
      })
    },
    async saveVipCoupon(params) {
      // 保存超级会员优惠券
      await saveVipCoupon(params)
      this.$message.success('保存成功')
      setTimeout(() => {
        this.$router.push({ path: '/member/coupon/list' })
      }, 1000)
    },
    handleShopCancel() {
      // 取消选择供应商
      this.dialogShopVisible = false
      this.$refs.shopDialog.visible = false
    },
    handleGoodCancel() {
      // 取消编辑商品
      this.dialogGoodVisible = false
      this.$refs.goodDialog.visible = false
    },
    handleAddList() {
      // 新增优惠券
      this.form.formList.push(defaultForm())
    },
    handleDelete(item, index) {
      // 删除单挑优惠券
      if (this.delFlag) {
        this.delCoupon(item.id, index)
      } else {
        this.form.formList.splice(index, 1)
      }
    },
    async delCoupon(id, index) {
      // 保存超级会员优惠券
      await delCoupon(id)
      this.form.formList.splice(index, 1)
    },
    handleOnInputBlur(formItem) {
      // 商品排序
      formItem.associateList.sort(this.sortByEnent('sort'))
    },
    sortByEnent(i) {
      // 排序
      return function(a, b) {
        return a[i] - b[i] //  a[i] - b[i]为正序，倒叙为  b[i] - a[i]
      }
    },
    handlePcStatusChange(row) {
      // PC状态开启关闭
      console.log('row', row)
      if (row.pcStatus === '0') {
        row.pcStatus = '1'
      } else {
        row.pcStatus = '0'
      }
    },
    handleAppStatusChange(row) {
      // 小程序状态开启关闭
      if (row.appletsStatus === '0') {
        row.appletsStatus = '1'
      } else {
        row.appletsStatus = '0'
      }
    },
    disabled3(array) {
      if (array && array.length >= 2) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

<style>
.form-cell{
  border: 1px solid #e1e1e1;
  border-radius: 8px;
  box-sizing: border-box;
  box-shadow: 0px 3px 6px 0px rgba(0, 0, 0, 0.07);
  padding: 20px;
  position: relative;
  margin-bottom: 20px;
}
.delete_label{
  position: absolute;
  right: 2%;
  top: 20px;
}
</style>
