<!-- 新增发票 -->
<template>
  <view class="invoice">
    <!-- 导航栏 -->
    <u-navbar
      title-color="#fff"
      :custom-back="customBack"
      :border-bottom="false"
      back-icon-color="#CCE8FF"
      :background="{ background: '#008CFF' }"
      title="开发票"
    />
    <view class="invoice-form">
      <u-form :model="form" :rules="rules" ref="uForm" label-width="150" label-align="right">
        <u-form-item label="抬头：" required>
          <u-radio-group v-model="queryParams.invoHeadType" @change="invoTypeChange">
            <u-radio :name="1">企业</u-radio>
            <u-radio :name="2">个人</u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item label="抬头名称：" prop="invoName" required>
          <u-input v-model="form.invoName" placeholder="请选择发票抬头" border disabled />
          <u-icon slot="right" name="list-dot" size="40" color="#606266" @click="moreCompany" />
        </u-form-item>
        <u-form-item label="税号：" prop="invoCode" required v-if="queryParams.invoHeadType === 1">
          <u-input v-model="form.invoCode" placeholder="税号自动填充" border disabled />
        </u-form-item>
        <u-form-item label="更多内容：" prop="moreContentValue">
          <u-input v-model="moreContentPop.moreContentValue" placeholder="开户银行、银行账号等" border disabled />
          <u-icon slot="right" name="arrow-right" size="36" color="#606266" @click="moreContent" />
        </u-form-item>
        <u-form-item label="发票金额："> ￥{{ form.amount }} </u-form-item>
      </u-form>
    </view>
    <view class="invoice-form margin-top">
      <u-form :model="form" ref="uForm1" label-width="150" label-align="right">
        <u-form-item label="电子邮箱：" prop="invoMail">
          <u-input v-model="form.invoMail" placeholder="选填" border />
        </u-form-item>
        <u-form-item label="手机号码：" prop="invoPhone">
          <u-input v-model="form.invoPhone" placeholder="选填" border />
        </u-form-item>
      </u-form>
    </view>
    <view class="invoice-submit">
      <u-button type="primary" :loading="loading" @click="submitForm">提交</u-button>
    </view>
    <!-- 公司弹框 -->
    <u-popup v-model="companyPop.show" mode="bottom" :closeable="true" height="50vh">
      <view class="popup">
        <view class="popup-list" v-if="companyPop.list.length">
          <u-radio-group class="popup-list-group" v-model="companyPop.form.name" :wrap="true">
            <u-radio class="popup-list-item" v-for="(item, index) in companyPop.list" :key="index" :name="item.id" @change="companyRadioClick(item)">
              {{ item.invoName }}
            </u-radio>
          </u-radio-group>
        </view>
        <view class="popup-list" v-else>
          <view class="popup-list-item">暂无抬头，请先添加</view>
        </view>
        <view class="popup-bottom">
          <u-button type="primary" @click="addInvoiceHeader">添加常用发票抬头</u-button>
        </view>
      </view>
    </u-popup>
    <!-- 更多内容 -->
    <u-popup v-model="moreContentPop.show" mode="center" width="100%" height="100%">
      <view class="invoice-more-pop">
        <view class="invoice-more-pop-form">
          <u-form :model="moreContentPop.form" ref="uForm2" label-width="150" label-align="right">
            <u-form-item label="开户银行：" prop="openBank">
              <u-input v-model="form.openBank" placeholder="选填" border />
            </u-form-item>
            <u-form-item label="银行账号：" prop="numBank">
              <u-input v-model="form.numBank" placeholder="选填" border />
            </u-form-item>
            <u-form-item label="企业地址：" prop="mapCom">
              <u-input v-model="form.mapCom" placeholder="选填" border />
            </u-form-item>
            <u-form-item label="企业电话：" prop="phoneCom">
              <u-input v-model="form.phoneCom" placeholder="选填" border />
            </u-form-item>
          </u-form>
        </view>
        <view class="invoice-more-pop-submit">
          <u-button type="primary" @click="moreContentConfirm">确定</u-button>
        </view>
      </view>
    </u-popup>
    <!-- 可开票订单 -->
    <u-popup v-model="orderPop.show" mode="top" length="100%">
      <view class="order-box">
        <u-navbar
          back-text=""
          title="可开票订单"
          :background="orderPop.background"
          title-color="#fff"
          back-icon-color="#fff"
          :custom-back="orderCustomBack"
        />
        <z-paging ref="paging" :fixed="false" v-model="orderPop.list" @query="queryList">
          <view class="order-box-list">
            <view class="order-box-list-item" v-for="(item, index) in orderPop.list" :key="index" @click="radioClick(item)">
              <view class="left">
                <view class="left-radio small-radio">
                  <radio value="true" :checked="orderPop.currentIds.includes(item.id)" />
                </view>
                <view class="left-content">
                  <view class="left-content-item money">￥{{ item.amount }}</view>
                  <view class="left-content-item">{{ item.name }}</view>
                  <view class="left-content-item time">{{ $u.timeFormat(new Date(item.payTime), 'yyyy-mm-dd hh:MM:ss') }}</view>
                </view>
              </view>
              <view class="right">{{ item.vehicleNo }}</view>
            </view>
          </view>
          <view class="order-box-bottom" slot="bottom">
            <view class="order-box-bottom-radio small-radio">
              <radio value="true" :checked="orderPop.checkedAll" :disabled="this.orderPop.list.length === 0" @click="checkedChange" />本页全选
            </view>
            <view class="order-box-bottom-next">
              <u-button type="primary" size="medium" :disabled="!orderPop.currentIds.length" @click="nextStep">下一步</u-button>
            </view>
          </view>
        </z-paging>
      </view>
    </u-popup>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        invoName: '',
        invoCode: '',
        invoHeadId: '',
        invoMail: '',
        invoPhone: '',
        invoType: 1,
        phoneCom: '',
        mapCom: '',
        openBank: '',
        numBank: '',
        amount: '',
        orderIds: []
      },
      rules: {
        invoType: [{ required: true, message: '请选择发票类型', trigger: 'change' }],
        invoName: [{ required: true, message: '请输入抬头名称', trigger: 'blur' }],
        invoCode: [{ required: true, message: '请输入税号', trigger: 'blur' }]
      },
      companyPop: {
        show: false,
        form: {
          name: ''
        },
        list: []
      },
      loading: false,
      queryParams: {
        invoHeadType: 1
      },
      moreContentPop: {
        show: false,
        moreContentValue: ''
      },
      orderPop: {
        show: true,
        background: {
          backgroundColor: '#008CFF'
        },
        checkedAll: false,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          invoType: 1
        },
        list: [],
        currentIds: [],
        currentList: []
      }
    };
  },
  watch: {
    'orderPop.currentIds'(val) {
      this.orderPop.checkedAll = val.length === this.orderPop.list.length && val.length !== 0;
    },
    'orderPop.list'(val) {
      this.orderPop.checkedAll = val.length === this.orderPop.currentIds.length && val.length !== 0;
    }
  },
  onLoad(options) {
    const { invoType } = options;
    this.form.invoType = invoType;
    this.orderPop.queryParams.invoType = invoType;
  },
  onShow() {
    this.getInvoiceHeaderSelect();
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    /**
     * @description: 订单关闭
     * @return {*}
     */
    orderCustomBack() {
      this.$u.route({
        url: '/pages/invoiceModule/myInvoice/myInvoice'
      });
    },
    /**
     * @description: 分页触发
     * @param {*} pageNo
     * @param {*} pageSize
     * @return {*}
     */
    queryList(pageNo, pageSize) {
      this.orderPop.queryParams.pageNum = pageNo;
      this.orderPop.queryParams.pageSize = pageSize;
      this.getList();
    },
    /**
     * @description: 获取列表
     * @return {*}
     */
    async getList() {
      const { code, data } = await this.$u.api.invoiceModuleApi.getInvoiceOrderListApi({ ...this.orderPop.queryParams });
      if (code === 200) {
        this.$refs.paging.complete(data?.pageInfo?.rows || []);
      }
    },
    /**
     * @description: 单项条目点击
     * @param {*} item
     * @return {*}
     */
    radioClick(item) {
      if (this.orderPop.currentIds.includes(item.id)) {
        const index = this.orderPop.currentIds.indexOf(item.id);
        this.orderPop.currentIds.splice(index, 1);
        this.orderPop.currentList.splice(index, 1);
      } else {
        this.orderPop.currentIds.push(item.id);
        this.orderPop.currentList.push(item);
      }
    },
    /**
     * @description: 全选
     * @return {*}
     */
    checkedChange() {
      this.orderPop.checkedAll = !this.orderPop.checkedAll;
      this.orderPop.currentIds = this.orderPop.checkedAll ? this.orderPop.list.map((item) => item.id) : [];
      this.orderPop.currentList = this.orderPop.checkedAll
        ? this.orderPop.list.map((item) => {
            return { ...item };
          })
        : [];
    },
    /**
     * @description: 下一步
     * @return {*}
     */
    nextStep() {
      if (this.orderPop.currentIds.length) {
        this.form.amount = this.countSum(this.orderPop.currentList);
        this.form.orderIds = this.orderPop.currentIds;
        this.orderPop.show = false;
      } else {
        this.$refs.uToast.show({
          title: '请先选择订单',
          type: 'warning'
        });
      }
    },
    /**
     * @description: 计算累加精度丢失问题
     * @param {*} arr
     * @return {*}
     */
    countSum(arr) {
      if (!arr.length) return 0;
      arr = arr.map((v) => {
        if (v.amount && !Number.isNaN(Number(v.amount))) return Math.round(v.amount.toFixed(2) * 100);
        return 0;
      });
      const result = arr.reduce((prev, curr) => {
        return prev + curr;
      }, 0);
      return result / 100;
    },
    /**
     * @description: 选择企业
     * @return {*}
     */
    moreCompany() {
      this.companyPop.show = true;
    },
    customBack() {
      this.orderPop.show = true;
      // uni.navigateBack();
    },
    moreContent() {
      this.moreContentPop.show = true;
    },
    /**
     * @description: 获取发票抬头下拉
     * @return {*}
     */
    async getInvoiceHeaderSelect() {
      const { code, data } = await this.$u.api.invoiceModuleApi.getInvoiceHeadSelectApi({ ...this.queryParams });
      if (code === 200) {
        this.companyPop.list = data;
        const { invoName, invoCode, id, invoMail, invoPhone, invoStatus } = data[0] || {};
        const isEmpty = invoStatus !== 1;
        this.form.invoName = isEmpty ? '' : invoName;
        this.form.invoCode = isEmpty ? '' : invoCode;
        this.form.invoHeadId = isEmpty ? '' : id;
        this.form.invoMail = isEmpty ? '' : invoMail;
        this.form.invoPhone = isEmpty ? '' : invoPhone;
        this.companyPop.form.name = isEmpty ? '' : id;
      }
    },
    /**
     * @description: 选择抬头
     * @param {*} item
     * @return {*}
     */
    companyRadioClick(item) {
      this.companyPop.show = false;
      this.form.invoName = item.invoName;
      this.form.invoCode = item.invoCode;
      this.form.invoHeadId = item.id;
      this.form.invoMail = item.invoMail;
      this.form.invoPhone = item.invoPhone;
      this.companyPop.form.name = item.id;
    },
    addInvoiceHeader() {
      this.companyPop.show = false;
      this.$u.route({
        url: '/pages/invoiceModule/invoiceHeaderList/invoiceHeaderList',
        params: {
          invoType: this.form.invoType
        }
      });
    },
    /**
     * @description: 抬头类型切换
     * @param {*} val
     * @return {*}
     */
    invoTypeChange(val) {
      this.queryParams.invoHeadType = val;
      this.getInvoiceHeaderSelect();
    },
    /**
     * @description: 更多内容弹框确认
     * @return {*}
     */
    moreContentConfirm() {
      this.moreContentPop.show = false;
      const { openBank, numBank, mapCom, phoneCom } = this.form;
      const moreContentTotal = [openBank, numBank, mapCom, phoneCom].filter(Boolean).length;
      this.moreContentPop.moreContentValue = moreContentTotal ? `共4项 已填写${moreContentTotal}项` : '';
    },
    submitForm() {
      this.$refs.uForm.validate(async (valid) => {
        if (!valid) return;
        try {
          this.loading = true;
          uni.showLoading({
            title: '提交中...'
          });
          const { invoHeadId, invoName, invoCode, invoMail, invoPhone, invoType, phoneCom, mapCom, openBank, numBank, orderIds } = this.form;
          const { code } = await this.$u.api.invoiceModuleApi.addInvoiceApi({
            invoHeadId,
            invoName,
            invoCode,
            invoMail,
            invoPhone,
            invoType,
            phoneCom,
            mapCom,
            openBank,
            numBank,
            orderIds
          });
          if (code === 200) {
            this.$refs.uToast.show({
              title: '添加成功!',
              type: 'success',
              duration: 1000
            });
            setTimeout(() => {
              uni.redirectTo({
                url: `/pages/invoiceModule/invoiceSuccess/invoiceSuccess`
              });
              uni.hideLoading();
              this.loading = false;
            }, 1000);
          }
        } catch (error) {
          uni.hideLoading();
          this.loading = false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import './addInvoice.scss';
</style>
