<!--
 * @Description: 新增/编辑弹框
 * @Author: Sugar.
 * @Date: 2023-11-24 13:55:00
 * @LastEditors: Sugar.
 * @LastEditTime: 2023-11-24 13:55:00
 * @FilePath: \cattle_webui\src\views\seatTypeMr\venueMr\dialog\AddOrEditDialog.vue
 * @Copyright: Copyright (c) 2016~2023 by Sugar., All Rights Reserved.
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="700px"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
  >
    <div class="dialog">
      <el-form :model="form" ref="form" :rules="rules" label-width="120px">
        <el-form-item label="场馆名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="场馆名称"
            :disabled="openType == 'see'"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="场馆图片" prop="showImg">
          <el-upload
            ref="upload"
            class="avatar-uploader"
            :action="uploadObj.url"
            :headers="uploadObj.headers"
            :show-file-list="false"
            accept=".jpg,.png"
            :disabled="openType == 'see'"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <div class="avatar" v-if="form.showImg">
              <el-image
                style="width: 100px; height: 100px"
                :src="form.showImg"
                fit="cover"
              />
            </div>
            <div class="upload-btn" v-else>
              <i class="el-icon-plus"></i>
              <div class="upload-btn-text">上传照片</div>
            </div>
            <div v-if="openType != 'see'"  class="el-upload__tip" slot="tip">只能上传.jpg或.png格式</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input
            v-model="form.contactName"
            placeholder="负责人"
            clearable
            :disabled="openType == 'see'"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="负责人联系电话">
          <el-input
            v-model="form.contactMobile"
            placeholder="负责人联系电话"
            clearable
            :disabled="openType == 'see'"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="客服电话">
          <el-input
            v-model="form.customerServiceMobile"
            placeholder="客服电话"
            clearable
            :disabled="openType == 'see'"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="场馆位置" prop="address">
          <span>{{form.address}}</span>
          <el-button v-if="openType != 'see'" type="text" style="padding-left: 10px" @click="initMapConfirm">去标注</el-button>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer" v-if="openType != 'see'">
      <el-button @click="cancel">取消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        v-loading.fullscreen.lock="loading"
        element-loading-text="提交中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <span v-if="loading">提交中...</span>
        <span v-else>保存</span>
      </el-button>
    </span>
    <span slot="footer" class="dialog-footer" v-if="openType == 'see'">
      <el-button type="primary" @click="cancel">确定</el-button>
    </span>

    <amap :visible="amapVisible" :default-value="form.address" :business-province-id="basicFormValidate.businessProvinceId" @getPosition="mapConfirm" />
  </el-dialog>
</template>

<script>
// import { updateNoticeMgr } from "@/api/system/noticeMgr";
import { getSelectById, saveAndEdit } from '@/api/venueMr/venueMr'
import Editor from "@/components/Editor";
import { getToken } from "@/utils/auth";
import amap from '@/components/aMap/index.vue'
export default {
  name: "addAndEdit",
  props: {
    dict: {
      type: Object,
      default: () => [],
    },
  },
  components: {
    amap,
    Editor,
  },
  data() {
    var isPhoneContact = (rule, value, callback) => {
      let reg = /^1[23456789]\d{9}$/;
      let reg1 = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/;
      if (!reg.test(value)) {
        if(reg1.test(value)){
          callback();
        }
        callback(new Error('请输入负责人联系电话'));
      } else {
        callback();
      }
    };
    var isPhoneService = (rule, value, callback) => {
      let reg = /^1[23456789]\d{9}$/;
      let reg1 = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/;
      if (!reg.test(value)) {
        if(reg1.test(value)){
          callback();
        }
        callback(new Error('请输入客服电话'));
      } else {
        callback();
      }
    };
    return {
      amapVisible: false,
      title: "编辑",
      model: "EDIT",
      open: false,
      loading: false,
      form: {
        id: undefined,
        type: "",
        content: "",
      },
      rules: {
        name: [{ required: true, message: "请输入场馆名称", trigger: ["change","blur"] }],
        showImg: [{ required: true, message: "请上传场馆图片", trigger: ["change","blur"] }],
        contactName: [{ required: true, message: "请输入负责人名称", trigger: ["change","blur"] }],
        contactMobile: [
          { required: true, message: "请输入负责人联系电话", trigger: ["change","blur"] },
          { validator: isPhoneContact, trigger: 'blur' }
        ],
        customerServiceMobile: [
          { required: true, message: "请输入客服电话", trigger: ["change","blur"] },
          { validator: isPhoneService, trigger: 'blur' }
        ],
        address: [{ required: true, message: "请选择场馆位置", trigger: ["change","blur"] }],
      },
      uploadObj: {
        url: process.env.VUE_APP_UPLOAD_FILE_API + "/upload/single/minio",
        Headers: { Authorization: "Bearer " + getToken() },
      },
      basicFormValidate: {},
      openType: 'add'
    };
  },
  methods: {
    initMapConfirm() {
      this.amapVisible = true
    },
    mapConfirm(flag, data) {
      this.amapVisible = false
      if (flag) {
        this.$set(this.form, 'address', data.address);
        this.$set(this.form, 'latitude', data.lat);
        this.$set(this.form, 'longitude', data.lng);
        this.basicFormValidate.businessProvinceId = data.businessProvinceId
      }
    },
    /**
     * 打开弹框
     * @date 2023-11-22
     * @param {any} obj
     * @returns {any}
     */
    openDialog(title, obj) {
      this.open = true;
      this.openType = "add"
      this.reset();
      if (obj){
        if(title == '查看数据'){
          this.title = "场馆管理";
          this.openType = "see"
        } else {
          this.title = "编辑场馆管理";
        }
        this.getSelectByIdApi(obj)
      }else{
        this.title = "添加场馆管理";
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      }
    },
    /** 获取详情 */
    getSelectByIdApi(row) {
      const id = row.id
      getSelectById(id).then(response => {
        const obj = response.data;
        this.$nextTick(() => {
          this.$set(this.form, 'id', obj.id);
          this.$set(this.form, 'name', obj.name);
          this.$set(this.form, 'showImg', obj.showImg);
          this.$set(this.form, 'contactName', obj.contactName);
          this.$set(this.form, 'contactMobile', obj.contactMobile);
          this.$set(this.form, 'customerServiceMobile', obj.customerServiceMobile);
          this.$set(this.form, 'address', obj.address);
        });
      });
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            let reg = /^1[23456789]\d{9}$/;
            // let reg1 = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/;
            let isContactMobile = false, isCustomerServiceMobile = false;
            if(this.form.contactMobile && this.form.contactMobile != ''){
              if (reg.test(this.form.contactMobile)) {
                isContactMobile = false;
              } else {
                isContactMobile = true;
              }
            }
            // if(this.form.customerServiceMobile && this.form.customerServiceMobile != ''){
            //   if (reg.test(this.form.customerServiceMobile)) {
            //     isCustomerServiceMobile = false;
            //   } else {
            //     isCustomerServiceMobile = true;
            //   }
            // }
            if(isContactMobile){
              this.$message.error("负责人联系电话验证失败");
              return false
            }
            // if(isCustomerServiceMobile){
            //   this.$message.error("客服电话验证失败");
            //   return false
            // }

            this.loading = true;
            const { code } = await saveAndEdit({ ...this.form });
            if (code === 200) {
              this.$message.success("操作成功!");
              this.$emit("getList");
              this.cancel();
            }
          } catch (error) {
          } finally {
            this.loading = false;
          }
        }
      });
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
    reset() {
      this.$set(this.form, 'id', "");
      this.$set(this.form, 'name', "");
      this.$set(this.form, 'showImg', "");
      this.$set(this.form, 'contactName', "");
      this.$set(this.form, 'contactMobile', "");
      this.$set(this.form, 'customerServiceMobile', "");
      this.$set(this.form, 'address', "");
    },
    /**
     * 关闭弹框
     * @date 2022-09-20
     * @returns {any}
     */
    cancel() {
      this.reset();
      this.open = false;
    },
    /**
     * 上传成功
     * @date 2023-11-22
     * @param {any} res
     * @returns {any}
     */
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        // this.form.mainImg = res?.data?.url;
        this.$set(this.form, 'showImg', res?.data?.url)
      }
    },
    /**
     * 上传文件之前之前
     * @date 2023-11-22
     * @param {any} file
     * @returns {any}
     */
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是jpg或png格式!");
      }
      return isJPG;
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  padding: 0 30px;
  max-height: 65vh;
  overflow-y: auto;
}
.dialog {
  padding: 0 30px;
  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;
    i {
      font-size: 30px;
      margin-top: 20px;
    }
    &-text {
      margin-top: -10px;
    }
  }
  .avatar {
    cursor: pointer;
  }
}
</style>
