<!--
 * @Description: 新增/编辑弹框
-->
<template>
  <el-dialog
    title="申请开票"
    v-if="isShow"
    :visible.sync="isShow"
    width="700px"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
  >
    <div class="dialog">
      <el-form :model="aduitForm" ref="aduitForm" :rules="formRules" label-width="150px">
        <el-form-item label="抬头类型" prop="handlerType">
          <el-radio-group v-model="aduitForm.handlerType" @input="changeType">
            <el-radio :label="2">企业</el-radio>
            <el-radio :label="1">个人</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="aduitForm.handlerType == 2" label="申请类型:" prop="invoiceLine">
          <el-select
            v-model="aduitForm.invoiceLine"
            placeholder="请选择申请类型"
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="dict in listType"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="抬头名称:" prop="name">
          <el-input
            v-model="aduitForm.name"
            placeholder="请输入抬头名称"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item v-if="aduitForm.handlerType == 2" label="税号:" prop="creditCode">
          <el-input
            v-model="aduitForm.creditCode"
            placeholder="请输入税号"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="电子邮箱:" prop="email">
          <el-input
            v-model="aduitForm.email"
            placeholder="请输入电子邮箱"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="发票金额(￥):" prop="invoiceAmount">
          <el-input
            v-model="aduitForm.invoiceAmount"
            placeholder="发票金额"
            disabled
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <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>
  </el-dialog>
</template>

<script>
import { 
  saveAndEdit,
} from '@/api/order/groupBuyingMr';
import Editor from "@/components/Editor";

export default {
  name: "addAndEdit",
  components: {
    Editor,
  },
  data() {
    let checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (value && !regEmail.test(value)) {
        callback(new Error('请输入有效的邮箱'));
      } else {
        callback(); // 确保调用 callback
      }
    };
    return {
      model: "EDIT",
      isShow: false,
      loading: false,
      aduitForm: {
        id: '',
        invoiceAmount: '',
        invoiceLine: '',
        handlerType: '',
        name: '',
        creditCode: '',
        mobile: '',
        email: ''
      },
      listType: [
          {
              "label": "数电专票",
              "value": 'bs',
          },
          {
              "label": "数电普票",
              "value": 'pc',
          },
      ],
      formRules: {
        name: [{ required: true, message: "请输入抬头名称", trigger: "blur" }],
        invoiceLine: [{ required: true, message: "请选择申请类型", trigger: "change" }], 
        email: [
          { required: true, message: "请输入电子邮箱", trigger: "blur" },
          {validator: checkEmail, trigger: "blur" }
        ],
        creditCode: [{ required: true, message: "请输入税号", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 打开弹框
    openDialog(title, obj, type) {
      this.isShow = true;
      // this.reset();
      this.$set(this.aduitForm, 'invoiceAmount', obj.realPrice || obj.invoiceAmount);
      this.$set(this.aduitForm, 'id', type ? obj.orderId: obj.id);
      this.$set(this.aduitForm, 'handlerType', 2);
      this.$nextTick(() => {
        if (this.$refs["aduitForm"]) {
          // console.log('表单已初始化');
          this.$refs["aduitForm"].clearValidate();
        }
      });
    },
    // 保存
    submitForm() {
      // console.log(this.$refs["aduitForm"], '111'); // 检查表单引用
      this.$refs["aduitForm"].validate((valid) => {
        if (valid) {
          try {
            this.loading = true;
            let params = {
              orderId: this.aduitForm.id,
              invoiceAmount: this.aduitForm.invoiceAmount,
              invoiceLine: this.aduitForm.invoiceLine,
              invoiceSource: 3,
              invoiceHandler: {
                handlerType: this.aduitForm.handlerType,
                name: this.aduitForm.name,
                creditCode: this.aduitForm.creditCode,
                mobile: this.aduitForm.mobile,
                email: this.aduitForm.email
              }
            };
            saveAndEdit({ ...params }).then(({ code }) => {
              if (code === 200) {
                this.$message.success("操作成功!");
                this.$emit("getList");
                this.cancel();
              }
            });
          } catch (error) {
            // console.error(error);
          } finally {
            this.loading = false;
          }
        } else {
          // console.error('表单校验失败');
        }
      });
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
    reset() {
      this.$set(this.aduitForm, 'id', "");
      this.$set(this.aduitForm, 'handlerType', '');
      this.$set(this.aduitForm, 'invoiceLine', "")
      this.$set(this.aduitForm, 'email', "");
      this.$set(this.aduitForm, 'name', "");
      this.$set(this.aduitForm, 'invoiceAmount', "");
      this.$set(this.aduitForm, 'creditCode', '');
    },
    // 关闭弹框
    cancel() {
      this.reset();
      this.isShow = false;
      if (this.$refs["aduitForm"]) {
        this.$refs["aduitForm"].resetFields();
      }
    },
    /**  选择抬头类型  */
    changeType(value) {
      if (value == 2) {
        // this.rules = {
        //   ...this.rules,
        //   creditCode: [{ required: true, message: "请输入税号", trigger: ["blur"] }]
        // };
        this.$set(this.aduitForm, 'invoiceLine', 'bs');

      } else {
        this.$set(this.aduitForm, 'invoiceLine', 'pc');
        this.$set(this.aduitForm, 'creditCode', '');
        delete this.rules.creditCode; // 移除 taxCode 校验规则  invoiceLine
        delete this.rules.invoiceLine; // 移除 taxCode 校验规则  invoiceLine
      }
      this.$nextTick(() => {
        if (this.$refs["aduitForm"]) {
          this.$refs["aduitForm"].clearValidate();
        }
      });
    }
    
  },
};
</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;
  }
}
.team_name_list {
  width: 100%;
  span {
    display: flex;
    width: 100%;
    padding: 5px 10px;
    cursor: pointer;
  }
  span:hover {
    color: #1890ff;
  }
}
</style>
