<template>
  <div>
    <el-dialog :visible.sync="visible" v-bind="modalOptions">
      <div>
        <el-form ref="formData" :model="formData" :rules="formRules" size="mini" label-suffix=":" label-width="160px">
          <div>
            <el-tabs v-model="activeName">
              <el-tab-pane label="授权信息" name="first">
                <el-form-item label="店铺名称" prop="shopName">
                  <el-input v-model="formData.shopName" maxlength="20" />
                </el-form-item>
                <el-form-item label="支持的支付类型" prop="payType">
                  <el-radio-group v-model="formData.payType">
                    <el-radio :label="9">惠市宝</el-radio>
                    <el-radio :label="4">通联</el-radio>
                    <el-radio :label="0">无</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="是否支持代金券" prop="isVoucher">
                  <el-radio-group v-model="formData.isVoucher">
                    <el-radio :label="1">
                      允许
                    </el-radio>
                    <el-radio :label="2">
                      拒绝
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  v-if="formData.isVoucher === 1" :rules="[
                    { required: true, message: '请输入代金券返还比例', trigger: 'blur' },
                    { type: 'number', max: 100, min: 0, message: '请输入正确的代金券返还比例，0 ~ 100', trigger: ['blur', 'change'] }
                  ]" label="代金券返还比例" prop="voucherReturn"
                >
                  <el-input v-model.number="formData.voucherReturn" style="width: 200px;" placeholder="请填写代金券返还比例，范围0 ~ 100">
                    <template #append>%</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="代金券提现比例" prop="voucherCoinRatio">
                  <el-input-number v-model="formData.voucherCoinRatio" :precision="2" :step="0.01" :max="1"></el-input-number>
                  <span style="margin-left: 10px;">比例*100</span>
                </el-form-item>
                <el-form-item label="是否支持消费金" prop="isBeeCoin">
                  <el-radio-group v-model="formData.isBeeCoin">
                    <el-radio :label="1">支持</el-radio>
                    <el-radio :label="2">不支持</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="formData.isBeeCoin === 1" label="商家消费金提现比例" prop="beeCoinRatio">
                  <el-input-number v-model="formData.beeCoinRatio" :precision="2" :step="0.01" :max="1"></el-input-number>
                  <span style="margin-left: 10px;">比例*100</span>
                </el-form-item>
                <el-form-item label="店铺负责人" prop="chargePersonName">
                  <el-input v-model="formData.chargePersonName" maxlength="20" />
                </el-form-item>
                <el-form-item label="负责人电话" prop="chargePersonPhone">
                  <!-- .replace(/(\d{3})\d+(\d{4})$/, '$1****$2') -->
                  <el-input v-model="formData.chargePersonPhone" maxlength="11" clearable />
                </el-form-item>
                <el-form-item label="请选择区域" prop="areaId">
                  <el-cascader
                    v-model="regionArrDialog" :props="regionProps" size="large" placeholder="请选择区域"
                    @change="formData.areaId = regionArrDialog[regionArrDialog.length - 1]"
                  ></el-cascader>
                  <div v-if="formData.areaId">已选ID：{{ formData.areaId }}</div>
                </el-form-item>
                <el-form-item label="官方分类" prop="classifyId">
                  <el-cascader
                    v-model="formData.classificationArr" placeholder="请选择官方分类" :options="categoryList"
                    :props="{ checkStrictly: false, expandTrigger: 'hover', label: 'storeName', value: 'id', children: 'childs' }"
                    clearable
                  />
                </el-form-item>
                <el-form-item label="店铺地址" prop="shopAdress">
                  <el-input v-model="formData.shopAdress" maxlength="60" />
                </el-form-item>
                <el-form-item label="店铺经纬度" prop="longitude">
                  <div>
                    <span v-if="formData.longitude">
                      {{ formData.longitude }} - {{ formData.latitude }}
                    </span>
                    <el-button
                      size="mini" type="primary" style="margin-left: 20px;"
                      @click="$refs.selectAddressMapRef && $refs.selectAddressMapRef.show()"
                    >
                      {{ formData.longitude ? '修改' : '选择' }}
                    </el-button>
                  </div>
                </el-form-item>
                <el-form-item label="生效日期" prop="effectiveDate">
                  <el-date-picker
                    v-model="formData.effectiveDate" value-format="yyyy-MM-dd" type="date"
                    placeholder="选择日期"
                  />
                </el-form-item>
                <el-form-item label="生效年限" prop="effectiveYear">
                  <el-input
                    v-model="formData.effectiveYear" type="text" placeholder="请输入内容" maxlength="4"
                    class="elipt"
                    style="width: 50%" show-word-limit
                  />
                  <span class="elspan">年</span>
                </el-form-item>
                <el-form-item label="合同状态" prop="contractState">
                  <el-radio-group v-model="formData.contractState">
                    <el-radio :label="1">
                      有效
                    </el-radio>
                    <el-radio :label="0">
                      无效
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="店铺类型" prop="shopType">
                  <el-radio-group v-model="formData.shopType">
                    <!-- <el-radio :label="1">品牌厂家</el-radio> -->
                    <el-radio :label="2">本地</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  v-if="formData.shopType === 2" prop="startTime" label="营业开始时间" :rules="[
                    { required: true, message: '请选择营业开始时间', trigger: 'blur' }
                  ]"
                >
                  <el-time-select
                    v-model="formData.startTime" placeholder="起始时间"
                    :picker-options="{ start: '00:00', step: '00:05' }"
                  >
                  </el-time-select>
                </el-form-item>
                <el-form-item
                  v-if="formData.shopType === 2" prop="endTime" label="营业结束时间" :rules="[
                    { required: true, message: '请选择营业结束时间', trigger: 'blur' }
                  ]"
                >
                  <el-time-select
                    v-model="formData.endTime" placeholder="营业结束时间"
                    :picker-options="{ start: '00:00', step: '00:05', end: '24:00' }"
                  >
                  </el-time-select>
                </el-form-item>
                <el-form-item label="惠市宝商家编号">
                  <el-input v-model="formData.hsbMrchId" maxlength="60" />
                </el-form-item>
                <el-form-item label="直播间审核" prop="auditLive">
                  <el-radio-group v-model="formData.auditLive">
                    <el-radio :label="1">开启</el-radio>
                    <el-radio :label="0">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="直播间商品审核" prop="auditLiveProduct">
                  <el-radio-group v-model="formData.auditLiveProduct">
                    <el-radio :label="1">
                      开启
                    </el-radio>
                    <el-radio :label="0">
                      关闭
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="兑换商品是否需要核销" prop="exchangeIsNeedVerification">
                  <el-radio-group v-model="formData.exchangeIsNeedVerification">
                    <el-radio :label="1">
                      是
                    </el-radio>
                    <el-radio :label="0">
                      否
                    </el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item class="b-shop-rate" prop="score" label="评分">
                  <el-rate v-model="formData.score"></el-rate>
                </el-form-item>

                <el-form-item prop="monthlySales" label="月售">
                  <el-input v-model.number="formData.monthlySales" placeholder="请输入商家月售额" type="number"></el-input>
                </el-form-item>

                <el-form-item prop="perCapita" label="人均">
                  <el-input v-model.number="formData.perCapita" type="number" placeholder="请输入人均消费额" closeable></el-input>
                </el-form-item>

                <el-form-item prop="shopBrief" label="商家简介">
                  <el-input
                    v-model="formData.shopBrief" autosize maxlength="250" show-word-limit
                    type="textarea"
                    placeholder="请输入商家简介" closeable
                  ></el-input>
                </el-form-item>

                <el-form-item prop="advertisement" label="广告图">
                  <!-- <el-upload
                    class="avatar-uploader" list-type="picture-card" :file-list="formData.advertisement"
                    :action="uploadUrl"
                    :on-success="(r) => formData.advertisement.push({ url: r.url, uid: r.url + Math.random() + Date.now() })"
                    :on-remove="(e) => formData.advertisement.filter((item) => item.uid !== e.uid)"
                    >
                    <i class="el-icon-plus avatar-uploader-icon" />
                    </el-upload> -->

                  <el-upload
                    class="avatar-uploader" list-type="picture-card" :file-list="uploadList"
                    :action="uploadUrl"
                    :on-success="uploadSuccess"
                    :on-remove="removeSuccess"
                  >
                    <i class="el-icon-plus avatar-uploader-icon" />
                  </el-upload>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="客户信息" name="second">
                <el-form-item label="账号" prop="shopPhone" maxlength="20">
                  <el-input ref="shopPhoneCls" v-model="formData.shopPhone" maxlength="20" />
                </el-form-item>
                <el-form-item label="密码" prop="shopPassword">
                  <el-input v-model="formData.shopPassword" type="password" maxlength="16" />
                </el-form-item>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="mini" @click="handleClose">取 消</el-button>
          <el-button v-if="activeName === 'first'" type="primary" size="mini" @click="activeName = 'second'">
            下一步
          </el-button>
          <el-button v-else-if="activeName === 'second'" type="primary" size="mini" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择经纬度 -->
    <SelectAddressMap
      ref="selectAddressMapRef"
      @select="(address) => (formData.longitude = address[0]) && (formData.latitude = address[1])"
    ></SelectAddressMap>
  </div>
</template>

<script>
import SelectAddressMap from './SelectAddressMap'
import { businessListGetById, businessListUpdate, businessListSave, businessClassList } from '@/api/business'
import { getProvinceList, getChildAreaList } from '@/api/address'
import { uploadUrl } from '@/utils/request'
import XeUtils from 'xe-utils'

export default {
  name: 'EditModal',
  components: {
    SelectAddressMap
  },
  data() {
    return {
      modalOptions: {
        closeOnClickModal: false,
        width: '820px',
        title: ''
      },
      visible: false,
      formData: {
        shopId: '',
        shopName: '', // 店铺名称
        voucherCoinRatio: '', // 代金券提现比例
        isBeeCoin: '', // 是否支持消费金
        beeCoinRatio: '', // 商家消费金提现比例
        chargePersonName: '', // 店铺负责人
        chargePersonPhone: '', // 负责人电话
        shopAdress: '', // 地址
        effectiveDate: '', // 生效日期
        effectiveYear: '', // 生效年限
        shopType: 2, // 商家类型 1 商家 2 本地
        payType: 0, // 支付类型
        isVoucher: 1, // 是否支持代金卷 1 true 2 false
        voucherReturn: '',
        contractState: 1, // 合同状态 1-有效 0-无效
        auditLive: 1,
        auditLiveProduct: 1,
        exchangeIsNeedVerification: 0,
        shopPhone: '', // 账号
        shopPassword: '', // 密码
        perCapita: '', // 人均
        score: '', // 评分
        advertisement: [], // 广告图
        areaId: '', // 区域id
        hsbMrchId: '', // 惠市宝商家编号，不是必填
        longitude: '', // 经纬度
        latitude: '', // 经纬度
        classificationId: '', // 商家分类id
        classificationArr: [], // 非后端参数
        startTime: '',
        endTime: '',
        shopBrief: '', // 商家简介
        monthlySales: ''
      },
      formRules: {
        shopName: [ { required: true, message: '请输入店铺名称' } ],
        effectiveDate: [ { required: true, message: '请输入生效日期' } ],
        effectiveYear: [ { required: true, message: '请输入生效年限' } ],
        chargePersonName: [ { required: true, message: '请输入店铺负责人', trigger: 'blur' } ],
        chargePersonPhone: [
          { required: true, message: '请输入负责人电话', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '目前只支持中国大陆的手机号码' }
        ],
        shopAdress: [ { required: true, message: '请输入地址', trigger: 'blur' } ],
        contractState: [ { required: true, message: '请选择合同状态', trigger: 'change' } ],
        shopType: [ { required: true, message: '请选择店铺类型', trigger: 'change' } ],
        perCapita: [ { required: true, message: '请输入人均消费额', trigger: 'blur' } ],
        shopBrief: [ { required: true, message: '请填写商家介绍', trigger: 'blur' } ],
        isVoucher: [ { required: true, message: '请选择是否允许使用代金卷', trigger: 'change' } ],
        auditLive: [ { required: true, message: '请选择状态', trigger: 'change' } ],
        auditLiveProduct: [ { required: true, message: '请选择状态', trigger: 'change' } ],
        exchangeIsNeedVerification: [ { required: true, message: '请选择状态', trigger: 'change' } ],
        score: [ { required: true, message: '请选择商家评分', trigger: 'change' } ],
        monthlySales: [ { required: true, message: '请输入商家月售额', trigger: 'blur' } ],
        // advertisement: [ { required: true, message: '请上传广告图', trigger: 'trigger' } ],
        // classificationArr: [ { required: true, type: 'array', message: '请选择分类' } ],
        areaId: [ { required: true, message: '请选择地址', trigger: 'blur' } ],
        longitude: [ { required: true, message: '请选择商家经纬度', trigger: 'blur' } ],
        isBeeCoin: [ { required: true, message: '请选择是否支持消费金' } ],
        beeCoinRatio: [],
        shopPhone: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '目前只支持中国大陆的手机号码' }
        ],
        shopPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^[~!@#$%^&*\-+=_.0-9a-zA-Z]{8,16}$/, message: '8-16密码数字英文混合' }
        ]
      },
      activeName: 'first',
      regionArrDialog: [],
      regionProps: {
        lazy: true,
        label: 'name',
        value: 'id',
        lazyLoad(node, resolve) {
          const { level, value } = node
          if (level === 0) {
            getProvinceList().then((res) => {
              resolve(res.data)
            })
          } else if (level != 0) {
            getChildAreaList(value).then((res) => {
              resolve(res.data.map((item) => {
                item.leaf = level === 3
                return item
              }))
            })
          }
        }
      },
      uploadUrl,
      categoryList: [],
      uploadList: []
    }
  },
  watch: {
    'formData.isBeeCoin': {
      deep: true,
      handler(val) {
        if (val === 1) {
          this.formRules.beeCoinRatio = [
            { required: true, message: '请输入商家消费金提现比例' },
            { pattern: /^0\.\d{0,2}$|^[1-9]\d*\.\d{0,2}$|^[1-9]\d*$/, message: '数值有误' }
          ]
        } else {
          this.formRules.beeCoinRatio = []
        }
      }
    }
  },
  created() {
    this.getCategoryTreeList()
  },
  methods: {
    handleClose() {
      this.visible = false
    },
    async getCategoryTreeList() {
      const res = await businessClassList({ page: 1, pageSize: 9999 })
      XeUtils.eachTree(res.data.records, (item) => {
        if (Array.isArray(item.childs) && item.childs.length === 0) {
          item.childs = undefined
        }
      }, { children: 'childs' })
      this.categoryList = res.data.records
    },
    initList() {
    },
    handleOpen(params = {}) {
      this.modalOptions.title = params.shopId ? '修改商家' : '新增商家'
      this.formData = Object.assign(this.$options.data().formData, params, {
        // advertisement: params.advertisement ? params.advertisement.split(',').map((item) => ({ url: item, uid: item + Math.random() + new Date() })) : []
      })
      // this.uploadList = this.formData.advertisement.split("&")
      const categoryItem = XeUtils.findTree(this.categoryList, (item) => item.id === String(params.classificationId))
      if (categoryItem && Array.isArray(categoryItem.nodes)) {
        this.formData.classificationArr = categoryItem.nodes.map((v) => v.id)
      }
      if (this.formData.areaId) this.regionArrDialog = [ this.formData.areaId ]
      this.visible = true
      this.initList()
      if (params.shopId) {
        this.getInfo(params.shopId)
      } else {
        this.$refs.formData && this.$refs.formData.resetFields()
      }
    },
    async getInfo(id) {
      const loading = this.$loading({ text: '加载中' })
      try {
        const res = await businessListGetById({ shopId: id })
        this.formData = Object.assign(this.$options.data().formData, res.data, {
          shopId: res.data.shopId || '',
          voucherReturn: Number(res.data.voucherReturn)
          // advertisement: res.data.advertisement ? res.data.advertisement.split(',').map((item) => ({ url: item, uid: item + Math.random() + new Date() })) : []
          // advertisement
        })
        const arr = this.formData.advertisement.split(',')
        if (arr[0] == '') {
          this.uploadList = []
        } else {
          this.uploadList = arr.map((item) => ({
            url: item,
            uid: item + Math.random() + new Date()
          }))
        }
        const categoryItem = XeUtils.findTree(this.categoryList, (item) => item.id === String(res.data.classificationId))
        if (categoryItem && Array.isArray(categoryItem.nodes)) {
          this.formData.classificationArr = categoryItem.nodes.map((v) => v.id)
        }
        if (this.formData.areaId) this.regionArrDialog = [ this.formData.areaId ]
        this.$nextTick(() => {
          this.$refs.formData && this.$refs.formData.validate()
        })
      } finally {
        loading.close()
      }
    },
    handleSubmit() {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({ text: '加载中' })
          try {
            const { advertisement, classificationArr, ...otps } = this.formData
            const params = {
              ...otps,
              // advertisement: Array.isArray(advertisement) ? advertisement.map((v) => v.url || v).join(',') : '',
              classificationId: Array.isArray(classificationArr) && classificationArr.length ? classificationArr[classificationArr.length - 1] : ''
            }
            params.advertisement = this.uploadList.reduce((prev, item, index) => {
              prev += item.url + ','
              return prev
            }, '')
            //  删除最后一个字符
            params.advertisement = params.advertisement.substring(0, params.advertisement.length - 1)
            this.formData.shopId ? await businessListUpdate(params) : await businessListSave(params)
            loading.close()
            this.$message({ message: `${this.formData.shopId ? '编辑' : '添加'}成功!`, type: 'success' })
            this.$emit('success')
            this.visible = false
          } catch (e) {
            loading.close()
          } finally {
            loading.close()
          }
        } else {
          this.$message({ message: '请输入相关信息', type: 'warning' })
          return false
        }
      })
    },
    uploadSuccess(r) {
      console.log(r)
      this.uploadList.push({ url: r.data.url, uid: r.url + Math.random() + Date.now() })
    },
    removeSuccess(r) {
      this.uploadList = this.uploadList.filter((item) => item.uid !== r.uid)
    }
  }
}
</script>
