<template>
  <div class="invoice-add">
    <div class="invoice-add__header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in $route.matched"
          :key="index"
          :to="{ path: item.path }"
          >{{ item.name }}</el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <div class="invoice-add__body">
      <el-form
        :rules="rules"
        class="invoice-content"
        ref="form"
        :model="form"
        label-width="120px"
      >
        <div class="invoice-content__header">
          <el-form-item label="选择订单：" prop="orderGoodsIds"
            ><el-select
              required
              @change="changeSelect"
              class="select"
              v-model="form.orderGoodsIds"
              clearable
              multiple
              placeholder="请选择"
            >
              <el-option
                v-for="item in orderList"
                :key="item.orderGoodsId"
                :label="
                  '商品名称：' +
                  item.goodsName +
                  ',订单编号:' +
                  item.orderSn +
                  ',价格:￥' +
                  item.goodsPrice
                "
                :value="item.orderGoodsId"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="合计金额：">
            <div class="total">
              <span class="note">￥{{ total }}</span>
            </div>
          </el-form-item>
        </div>

        <div class="invoice-content__header">
          <el-form-item label="发票类型：" required prop="type">
            <el-radio-group v-model="form.type" @change="changeType">
              <el-radio label="1">普通发票</el-radio>
              <el-radio label="2">增值税发票</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="申请主体：" required prop="type">
            <template v-if="form.type == 2">
              <el-radio v-model="form.subject" label="2">企业</el-radio>
            </template>
            <template v-else>
              <el-radio v-model="form.subject" label="1">个人</el-radio>
              <el-radio v-model="form.subject" label="2">企业</el-radio>
            </template>
          </el-form-item>
        </div>

        <div class="invoice-content__body">
          <el-form-item label="发票抬头：" required prop="invoiceTitle">
            <el-input v-model="form.invoiceTitle"></el-input>
          </el-form-item>

          <template v-if="form.subject == 2">
            <el-form-item
              label="纳税登记号："
              required
              prop="taxRegistryNumber"
            >
              <el-input v-model="form.taxRegistryNumber"></el-input>
            </el-form-item>
          </template>

          <template v-if="form.type == 2">
            <el-form-item label="单位地址：" required prop="companyAddress">
              <el-input v-model="form.companyAddress"></el-input>
            </el-form-item>
            <el-form-item label="电话号码：" required prop="phone">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
            <el-form-item label="开户银行：" required prop="bankName">
              <el-input v-model="form.bankName"></el-input>
            </el-form-item>
            <el-form-item label="银行账号：" required prop="bankAccount">
              <el-input v-model="form.bankAccount"></el-input>
            </el-form-item>
            <el-form-item label="收件地址：" required prop="receivingAddress">
              <el-input v-model="form.receivingAddress"></el-input>
            </el-form-item>

            <el-form-item label="收件人：" required prop="receivingName">
              <el-input v-model="form.receivingName"></el-input>
            </el-form-item>

            <el-form-item label="收件手机：" required prop="receivingTel">
              <el-input v-model="form.receivingTel"></el-input>
            </el-form-item>
          </template>
        </div>

        <div class="invoice-content__footer">
          <div class="invoice-price">
            本次申请开票金额（元）：
            <span class="note">{{ total }}</span>
          </div>
          <div class="btns">
            <el-button type="primary" plain round class="cancel" @click="cancel"
              >取消</el-button
            >
            <el-button
              type="primary"
              class="ok"
              :loading="loading"
              @click="submit"
              >提交申请</el-button
            >
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "MyInvoice",
  data() {
    return {
      form: {
        type: "1",
        subject: "1",
        invoiceTitle: "",
        taxRegistryNumber: "",
        companyAddress: "",
        phone: "",
        bankName: "",
        bankAccount: "",
        receivingAddress: "",
        receivingName: "",
        receivingTel: "",
        orderGoodsIds: [],
      },
      radio1: "",
      radio2: "",
      orderList: [],
      total: 0,
      rules: {
        receivingTel: [
          {
            required: true,
            message: "请输入收件手机",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
          {
            validator: (rule, value, callback) => {
              var reg_tel =
                /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
              if (reg_tel.test(value)) {
                return callback();
              } else {
                return callback(new Error("手机号码格式不正确"));
              }
            },
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
        type: [
          {
            required: true,
            message: "请选择发票类型",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        subject: [
          {
            required: true,
            message: "请选择申请主体",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        invoiceTitle: [
          {
            required: true,
            message: "请输入发票抬头",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        taxRegistryNumber: [
          {
            required: true,
            message: "请输入纳税登记号",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
          {
            validator: (rule, value, callback) => {
              var reg = /(^[0-9A-Z]{15,20}$)/;
              if (reg.test(value)) {
                return callback();
              } else {
                return callback(new Error("纳税登记号格式不正确"));
              }
            },
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
        companyAddress: [
          {
            required: true,
            message: "请输入单位地址",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        phone: [
          {
            required: true,
            message: "请输入电话号码",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        bankName: [
          {
            required: true,
            message: "请输入开户银行",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
          {
            validator: (rule, value, callback) => {
              var reg = /[\u4E00-\u9FA5]+/;
              if (reg.test(value)) {
                return callback();
              } else {
                return callback(new Error("开户银行名称不正确"));
              }
            },
            trigger: ["change", "blur"],
          },
        ],
        bankAccount: [
          {
            required: true,
            message: "请输入银行账号",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
          {
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              var reg = /^[1-9]{1}(\d{15}|\d{18})$/;
              if (reg.test(value)) {
                return callback();
              } else {
                return callback(new Error("银行卡号格式不正确"));
              }
            },
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
        receivingAddress: [
          {
            required: true,
            message: "请输入收件地址",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        receivingName: [
          {
            required: true,
            message: "请输入收件人",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
        orderGoodsIds: [
          {
            required: true,
            message: "请选择订单",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
      },

      loading: false,
    };
  },
  mounted() {
    this.orderInvoiceCanInvoiceList();
  },
  methods: {
    changeType(e) {
      if (this.form.type == "2") {
        this.form.subject = "2";
      } else {
        this.form.subject = "1";
      }
    },
    changeSelect(e) {
      let total = 0;
      this.form.orderGoodsIds.forEach((id) => {
        let orderItem = this.orderList.find((item) => item.orderGoodsId == id);
        if (orderItem) {
          total += orderItem.goodsPrice;
        }
      });

      this.total = total;
    },
    cancel() {
      this.$router.go(-1);
    },

    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.total > 10000) {
            this.$message({
              type: "warning",
              message:
                "您所选的订单总开票金额，大于10000元，超出单张发票的开票额度，请修改开票订单",
            });
            return;
          }

          this.loading = true;
          let data = JSON.parse(JSON.stringify(this.form));
          data.amount = this.total;
          if (data.subject == "1") {
            data.taxRegistryNumber = "";
            data.companyAddress = "";
            data.phone = "";
            data.bankName = "";
            data.bankAccount = "";
            data.receivingAddress = "";
            data.receivingName = "";
            data.receivingTel = "";
          }
          this.$request
            .orderInvoice(data)
            .then((res) => {
              this.loading = false;
              this.orderInvoiceCanInvoiceList();
              this.form = {
                type: "1",
                subject: "1",
                invoiceTitle: "",
                orderGoodsIds: [],
                taxRegistryNumber: "",
                companyAddress: "",
                phone: "",
                bankName: "",
                bankAccount: "",
                receivingAddress: "",
                receivingName: "",
                receivingTel: "",
              };
              this.total = 0;

              const confirmText = [
                "您本次的发票申请已经提交成功！",
                "机构将在3-7个工作日内进行处理，处理结果会在【发票记录】显示，请留意进度。",
              ];
              const newDatas = [];
              const h = this.$createElement;
              for (const i in confirmText) {
                newDatas.push(h("p", null, confirmText[i]));
              }
              this.$confirm(h("div", null, newDatas), "操作提示", {
                confirmButtonText: "知道了",
                closeOnClickModal: false,
                showCancelButton: false,
                closeOnPressEscape: false,
                distinguishCancelAndClose: false,
                showClose: false,
              })
                .then((_) => {})
                .catch((_) => {
                  console.log(_);
                });
            })
            .catch((err) => {
              this.loading = false;
              this.$message({
                type: "error",
                message: err.msg,
              });
            });
        }
      });
    },

    /**
     * 获取可开发票的订单
     */
    orderInvoiceCanInvoiceList() {
      this.$request.orderInvoiceCanInvoiceList().then((res) => {
        this.orderList = res.rows;
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.invoice-add {
  overflow: hidden;
  &__header {
    border-bottom: 1px solid #eee;
    margin-top: 24px;
    padding-bottom: 20px;
  }
  &__body {
    .invoice-content {
      &__header {
        margin-top: 20px;
        width: 1110px;
        padding: 10px 12px;
        background: #fafbfc;
        border: 1px solid #eeeeee;
        box-shadow: 0px 0px 7px 1px rgba(0, 0, 0, 0.04);
        border-radius: 8px;

        .select {
          width: 100%;
        }

        .total {
          font-size: 14px;

          .note {
            color: #ff3b30;
          }
        }
      }

      &__body {
        margin-top: 20px;
        width: 1110px;
        padding: 10px 12px;
        background: #fafbfc;
        border: 1px solid #eeeeee;
        box-shadow: 0px 0px 7px 1px rgba(0, 0, 0, 0.04);
        border-radius: 8px;
      }

      &__footer {
        margin-top: 20px;
        padding-bottom: 40px;

        .invoice-price {
          border-top: 1px solid #eee;
          border-bottom: 1px solid #eee;
          line-height: 50px;
          font-size: 18px;
          font-family: Microsoft YaHei;
          font-weight: 400;
          color: #333333;
          .note {
            font-size: 18px;
            color: #ff3b30;
            font-weight: bold;
            margin-left: 10px;
          }
        }

        .btns {
          margin-top: 20px;
          .cancel {
            padding: 0;
            display: inline-block;
            margin: 0 10px;
            cursor: pointer;
            width: 122px;
            height: 32px;
            border-radius: 16px;
            text-align: center;
            font-size: 16px;
            line-height: 30px;
          }

          .ok {
            padding: 0;
            display: inline-block;
            margin: 0 10px;
            cursor: pointer;
            width: 122px;
            height: 32px;
            border-radius: 16px;
            text-align: center;
            line-height: 32px;
            font-size: 16px;
          }
        }
      }
    }
  }
}
</style>
