<template>
  <el-row :gutter="10" v-loading="loading">
    <el-col :span="24" v-if="step === 1">
      <el-form
        ref="ruleForm1"
        :model="ruleForm1"
        :rules="rulesThis"
        label-width="110px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="13">
            <el-form-item label="申请公司" prop="companyNo">
              <el-select
                v-model="ruleForm1.companyNo"
                multiple
                filterable
                remote
                :disabled="disableds"
                :multiple-limit="1"
                reserve-keyword
                :size="searchSize"
                style="width: 100%"
                placeholder="公司名称搜索"
                :remote-method="remoteMethod"
                :loading="selectLoading"
                @change="selectChange($event, false)"
              >
                <el-option
                  v-for="item in activeOptions"
                  :key="item.companyNo"
                  :label="item.companyName"
                  :value="item.companyNo"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="发票抬头类型" prop="inv_add">
              <el-radio-group
                v-model="ruleForm1.inv_add"
                @change="invAddChange"
                :disabled="disableds"
              >
                <el-radio :label="'0'" :disabled="disableds"
                  >使用已有发票抬头</el-radio
                >
                <el-radio :label="'1'" :disabled="disableds"
                  >新建发票抬头</el-radio
                >
              </el-radio-group>
            </el-form-item></el-col
          >
          <el-col :span="24">
            <el-col :span="13">
              <el-form-item label="发票抬头" prop="invoice_title">
                <el-select
                  v-if="ruleForm1.inv_add === '0'"
                  v-model="ruleForm1.invoice_title"
                  multiple
                  filterable
                  remote
                  :disabled="disableds"
                  :multiple-limit="1"
                  reserve-keyword
                  :size="searchSize"
                  style="width: 100%"
                  placeholder="发票抬头搜索"
                  :remote-method="remoteMethod2"
                  :loading="selectLoading2"
                  @change="selectChange2"
                >
                  <el-option
                    v-for="item in activeOptions2"
                    :key="item.id"
                    :label="item.invoice_title"
                    :value="item.id"
                  />
                </el-select>
                <el-input
                  v-else
                  :disabled="disableds"
                  placeholder="请输入发票抬头"
                  v-model="ruleForm1.invoice_title"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="纳税登记证号" prop="invoice_code">
                <el-input
                  :disabled="ruleForm1.inv_add === '0' || disableds"
                  placeholder="请输入纳税登记证号"
                  v-model="ruleForm1.invoice_code"
                >
                </el-input
              ></el-form-item>
            </el-col>

            <el-col :span="13">
              <el-form-item label="开户银行名称" prop="invoice_bank">
                <el-input
                  :disabled="disableds"
                  placeholder="请输入开户银行名称"
                  v-model="ruleForm1.invoice_bank"
                >
                </el-input
              ></el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="开户银行账号" prop="invoice_bankNo">
                <el-input
                  :disabled="disableds"
                  placeholder="请输入开户银行账号"
                  v-model="ruleForm1.invoice_bankNo"
                >
                </el-input
              ></el-form-item>
            </el-col>
            <el-col :span="13">
              <el-form-item label="纳税登记地址" prop="invoice_addr">
                <el-input
                  :disabled="disableds"
                  placeholder="请输入纳税登记地址"
                  v-model="ruleForm1.invoice_addr"
                >
                </el-input
              ></el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="联系电话" prop="invoice_mobile">
                <el-input
                  :disabled="disableds"
                  placeholder="请输入联系电话"
                  v-model="ruleForm1.invoice_mobile"
                >
                  <el-select
                    v-model="schange"
                    slot="prepend"
                    style="width: 100px"
                    placeholder="请选择"
                    @change="selectChangeMobile"
                  >
                    <el-option
                      v-for="item in soptins"
                      :key="item.code + 'indexs'"
                      :label="item.name"
                      :value="item.code"
                    ></el-option>
                  </el-select> </el-input
              ></el-form-item>
            </el-col>
          </el-col>

          <el-col :span="13">
            <el-form-item label="发票类型" prop="inv_type">
              <el-select
                v-model="ruleForm1.inv_type"
                clearable
                :disabled="disableds"
                placeholder="请选择发票类型"
                style="width: 100%"
              >
                <el-option
                  v-for="item in invioceType"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="开票类型" prop="type">
              <el-select
                v-model="ruleForm1.type"
                :disabled="isDetail !== '003'"
                placeholder="请选择开票类型"
                style="width: 100%"
                @change="changetype"
              >
                <el-option
                  v-for="item in billType"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="销售方开票信息"
              label-width="125px"
              prop="inv_out"
            >
              <el-select
                v-model="ruleForm1.inv_out"
                :disabled="disableds"
                placeholder="请选择销售方开票信息"
                style="width: 100%"
              >
                <el-option
                  v-for="item in invoiceList"
                  :key="item.companyNo"
                  :label="item.company_name"
                  :value="item.companyNo"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12" v-if="ruleForm1.type === '2'">
            <el-form-item label="开票总金额" prop="total">
              <el-input-number
                step-strictly
                controls-position="right"
                style="width: 100%"
                :disabled="disableds"
                v-model="ruleForm1.total"
                :precision="2"
                :step="0.01"
                :min="0"
                :max="1000000000000"
              ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="ruleForm1.type === '2'">
            <el-form-item label="备注" prop="remark">
              <el-input
                :disabled="disableds"
                type="textarea"
                maxlength="250"
                show-word-limit
                :autosize="{ minRows: 6, maxRows: 6 }"
                placeholder="请输入商品明细要求： 商品分类，型号等信息"
                v-model="ruleForm1.remark"
              >
              </el-input></el-form-item
          ></el-col>

          <el-col :span="24">
            <el-row>
              <el-col :span="20" v-if="status === '2'">
                <el-alert
                  title="财务驳回理由："
                  type="error"
                  :closable="false"
                  :description="exam_remark"
                  show-icon
                >
                </el-alert>
              </el-col>
              <el-col :span="status === '2' ? 4 : 24" style="text-align: right">
                <el-button
                  type="primary"
                  v-if="ruleForm1.type !== '2'"
                  @click="submitForm1"
                  >下一步<i class="el-icon-arrow-right el-icon--right"></i
                ></el-button>
                <el-button
                  v-if="!disableds && ruleForm1.type === '2'"
                  type="primary"
                  @click="submitForm1"
                  >保 存
                </el-button>
              </el-col></el-row
            >
          </el-col>
        </el-row>
      </el-form>
    </el-col>
    <el-col :span="24" v-else-if="step !== 1 && ruleForm1.type === '1'">
      <el-row>
        <el-col
          :span="isDetail !== '003' ? 24 : 21"
          style="padding: 0 12px 8px 0"
        >
          <el-alert
            title="特别提示：请注意商品未核销数量/发票未核销金额。若此次核销的数量等于未核销数量，不论此次总金额核销后，发票未核销金额是否为0，都不能再使用该商品核销！发票核销总金额同理。"
            type="error"
            :closable="false"
            show-icon
          >
          </el-alert>
        </el-col>
        <el-col
          v-if="isDetail === '003'"
          :span="3"
          class="tr"
          style="padding: 11px 0 8px 0"
          ><el-button
            type="primary"
            class="fr"
            size="small"
            @click="openModal(1)"
            >添加产品确认单</el-button
          ></el-col
        >
        <el-col :span="24">
          <el-table
            style="width: 100%"
            :size="'mini'"
            :data="tableData"
            stripe
            highlight-current-row
            max-height="380"
            border
          >
            <el-table-column
              label="产品编号"
              prop="goodNo"
              show-overflow-tooltip
              width="155"
              fixed="left"
            >
            </el-table-column>
            <el-table-column
              label="商品名称"
              prop="goodname"
              show-overflow-tooltip
              min-width="120"
            >
            </el-table-column>
            <el-table-column
              label="开票商品名"
              width="160"
              prop="remark"
              show-overflow-tooltip
            />
            <el-table-column
              label="品牌"
              prop="brand"
              width="80"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              label="单位"
              prop="unit"
              width="80"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column label="单价" width="90" prop="price" />
            <el-table-column label="数量" align="center">
              <el-table-column label="总计" width="70" prop="num" />
              <el-table-column label="已核销" width="70" prop="inv_num" />
              <el-table-column label="未核销" width="70" prop="over_num" />
              <el-table-column label="此次核销" width="70" prop="good_num" />
            </el-table-column>

            <el-table-column
              label="总价"
              width="105"
              prop="total"
              show-overflow-tooltip
            />
            <el-table-column label="关联发票信息" align="center">
              <el-table-column
                label="已核销金额"
                width="100"
                prop="ainv_fee"
                show-overflow-tooltip
              />
              <el-table-column
                label="未核销金额"
                width="100"
                prop="winv_fee"
                show-overflow-tooltip
              />
              <el-table-column
                label="此次核销金额"
                width="100"
                prop="total_fee"
              />
            </el-table-column>

            <el-table-column
              fixed="right"
              label="操作"
              width="80"
              v-if="isDetail === '003' || isDetail === '005'"
            >
              <template slot-scope="scope">
                <el-tooltip
                  effect="dark"
                  v-if="isDetail === '003' || isDetail === '005'"
                  content="编辑"
                  placement="top"
                >
                  <i
                    v-if="isDetail === '003' || isDetail === '005'"
                    class="el-icon-edit tb-icon"
                    @click="editRow(scope.$index)"
                  ></i>
                </el-tooltip>
                <el-tooltip
                  effect="dark"
                  content="删除"
                  v-if="isDetail === '003'"
                  placement="top"
                >
                  <i
                    v-if="isDetail === '003'"
                    class="el-icon-delete tb-icon"
                    @click="deleteRow(scope.$index, tableData)"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="24" style="padding: 10px 0 0 0">
          <el-input
            :disabled="disableds"
            type="textarea"
            maxlength="250"
            show-word-limit
            :autosize="{ minRows: 3, maxRows: 3 }"
            placeholder="请输入其他要求"
            v-model="remark"
          />
        </el-col>
        <el-col :span="24" style="padding: 10px 0 0 0">
          <el-row>
            <el-col :span="19" v-if="status === '2'">
              <el-alert
                title="财务驳回理由："
                type="error"
                :closable="false"
                :description="exam_remark"
                show-icon
              >
              </el-alert>
            </el-col>
            <el-col :span="status === '2' ? 5 : 24" class="tr">
              <el-button type="primary" @click="step = 1"
                ><i class="el-icon-arrow-left el-icon--left"></i
                >上一步</el-button
              >
              <el-button v-if="!disableds" type="primary" @click="submitForm"
                >保 存
              </el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <order-change-dialog
        :id="modelId"
        :trade_status="''"
        :inv_status="'4'"
        :is-detail="isDetail"
        :show-model="showOrderModel"
        @refresh="orderRefresh"
        @cancel="showOrderModel = false"
      />
      <good-change-dialog
        :show-model="showGoodChangeModel"
        :item="activeItem"
        :is-detail="isDetail"
        @refresh="goodChangeEnd"
        @cancel="showGoodChangeModel = false"
      />
    </el-col>
    <el-col :span="24" v-else-if="step !== 1 && ruleForm1.type === '3'">
      <el-row>
        <el-col
          v-if="isDetail === '003'"
          :span="24"
          class="tr"
          style="padding: 11px 0 8px 0"
          ><el-button
            type="primary"
            class="fr"
            size="small"
            @click="openModal(2)"
            >添加资金</el-button
          ></el-col
        >
        <el-col :span="24">
          <el-table
            style="width: 100%"
            :size="'mini'"
            :data="capitalTableData"
            stripe
            highlight-current-row
            max-height="380"
            border
          >
            <el-table-column
              prop="traNo"
              label="资金编号"
              show-overflow-tooltip
              width="270"
            ></el-table-column>
            <el-table-column
              prop="customer"
              label="企业名称"
              show-overflow-tooltip
              min-width="170"
            ></el-table-column>
            <el-table-column
              prop="trade_out"
              label="付款方"
              show-overflow-tooltip
              min-width="170"
            ></el-table-column>
            <el-table-column
              prop="trade_used"
              label="付款备注"
              show-overflow-tooltip
              width="270"
            ></el-table-column>

            <el-table-column
              prop="total_fee"
              label="资金总额度"
              show-overflow-tooltip
              min-width="110"
            ></el-table-column>

            <el-table-column
              label="关联发票信息"
              show-overflow-tooltip
              align="center"
            >
              <el-table-column
                prop="inv_fee"
                label="已核销金额"
                show-overflow-tooltip
                min-width="110"
              ></el-table-column>
              <el-table-column
                prop="inv_used"
                label="处理中的金额"
                show-overflow-tooltip
                min-width="110"
              ></el-table-column>
              <el-table-column
                prop="winv_fee"
                label="未核销金额"
                show-overflow-tooltip
                min-width="110"
              ></el-table-column>
              <el-table-column
                label="核销状态"
                show-overflow-tooltip
                min-width="95"
              >
                <template slot-scope="scope">
                  <el-tag
                    type="danger"
                    :size="'mini'"
                    v-if="scope.row.inv_status === '1'"
                    >未核销</el-tag
                  >
                  <el-tag
                    type="warning"
                    :size="'mini'"
                    v-else-if="scope.row.inv_status === '2'"
                    >部分核销</el-tag
                  >
                  <el-tag type="" :size="'mini'" v-else>全部核销</el-tag>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column
              label="关联确认单信息"
              show-overflow-tooltip
              align="center"
            >
              <el-table-column
                prop="order_fee"
                label="已核销金额"
                show-overflow-tooltip
                min-width="110"
              ></el-table-column>
              <el-table-column
                prop="order_used"
                label="处理中的金额"
                show-overflow-tooltip
                min-width="110"
              ></el-table-column>
              <el-table-column
                prop="worder_fee"
                label="未核销金额"
                show-overflow-tooltip
                min-width="110"
              ></el-table-column>
              <el-table-column
                label="核销状态"
                show-overflow-tooltip
                min-width="95"
              >
                <template slot-scope="scope">
                  <el-tag
                    type="danger"
                    :size="'mini'"
                    v-if="scope.row.order_status === '1'"
                    >未核销</el-tag
                  >
                  <el-tag
                    type="warning"
                    :size="'mini'"
                    v-else-if="scope.row.order_status === '2'"
                    >部分核销</el-tag
                  >
                  <el-tag type="" :size="'mini'" v-else>全部核销</el-tag>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column
              prop="addtime"
              label="创建时间"
              show-overflow-tooltip
              width="150"
            ></el-table-column>

            <el-table-column
              fixed="right"
              label="操作"
              width="50"
              v-if="isDetail === '003'"
            >
              <template>
                <el-tooltip
                  effect="dark"
                  content="删除"
                  v-if="isDetail === '003'"
                  placement="top"
                >
                  <i
                    v-if="isDetail === '003'"
                    class="el-icon-delete tb-icon"
                    @click="deleteRow(scope.$index, 1)"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="24" style="padding: 10px 0 0 0">
          <el-input
            :disabled="disableds"
            type="textarea"
            maxlength="250"
            show-word-limit
            :autosize="{ minRows: 3, maxRows: 3 }"
            placeholder="请输入其他要求"
            v-model="remark"
          />
        </el-col>
        <el-col :span="24" style="padding: 10px 0 0 0">
          <el-row>
            <el-col :span="19" v-if="status === '2'">
              <el-alert
                title="财务驳回理由："
                type="error"
                :closable="false"
                :description="exam_remark"
                show-icon
              >
              </el-alert>
            </el-col>
            <el-col :span="status === '2' ? 5 : 24" class="tr">
              <el-button type="primary" @click="step = 1"
                ><i class="el-icon-arrow-left el-icon--left"></i
                >上一步</el-button
              >
              <el-button v-if="!disableds" type="primary" @click="submitForm2"
                >保 存
              </el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <capital-change-dialog
        :id="modelId"
        :order_status="''"
        :trade_status="''"
        :inv_status="'4'"
        :status="'3'"
        :show-model="showCapitalModel"
        @refresh="capitalRefresh"
        @cancel="showCapitalModel = false"
      />
    </el-col>
  </el-row>
</template>
<script>
import asyncRequest from "@/apis/service/InvoiceSales/invoiceApply";
import orderChangeDialog from "@/components/changeDialog/order";
import capitalChangeDialog from "@/components/changeDialog/capital";
import resToken from "@/mixins/resToken";
import goodChangeDialog from "./goodChangeDialog.vue";
import { isLicense, isqzf, isqz, iszf, isz, isMobile } from "@/utils/validate";
export default {
  name: "invoiceApply",
  props: ["showModel", "id", "isDetail", "newTime", "invNo", "status"],
  components: {
    orderChangeDialog,
    goodChangeDialog,
    capitalChangeDialog,
  },
  mixins: [resToken],
  data() {
    const validateLicense = (rule, value, callback) => {
      if (value !== "") {
        if (!isLicense(value)) {
          callback(new Error("纳税登记证号不正确！"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入纳税登记证号！"));
      }
    };

    const validatemobile = (rule, value, callback) => {
      if (value !== "") {
        // 区-固-分
        if (this.schange === "1") {
          if (isqzf(value)) {
            callback();
          } else {
            callback(
              new Error("规则为区号[0+2~3位]-固定电话[7~8位]-分机号[1~6位]！")
            );
          }
          //区-固
        } else if (this.schange === "2") {
          if (isqz(value)) {
            callback();
          } else {
            callback(new Error("规则为区号[0+2~3位]-固定电话[7~8位]！"));
          }
          //固-分
        } else if (this.schange === "3") {
          if (iszf(value)) {
            callback();
          } else {
            callback(new Error("规则为固定电话[7~8位]-分机号[1~6位]！"));
          }
          //固
        } else if (this.schange === "4") {
          if (isz(value)) {
            callback();
          } else {
            callback(new Error("规则为固定电话[7~8位]！"));
          }
          //手机号
        } else {
          if (!isMobile(value)) {
            callback(new Error("手机号格式不正确！"));
          } else {
            callback();
          }
        }
      } else {
        callback(new Error("请输入联系电话！"));
      }
    };
    return {
      disableds: false,
      modelId: "",
      showOrderModel: false,
      showCapitalModel: false,
      cwRes: null,
      invoiceList: [],
      tableData: [],
      capitalTableData: [],
      activeIndex: 0,
      activeItem: null,
      showGoodChangeModel: false,
      remark: "",
      exam_remark: "",
      step: 1,
      selectLoading: false,
      selectLoading2: false,
      loading: false,
      title: "添加发票申请",
      schange: "1",
      soptins: [
        {
          code: "1",
          name: "区-固-分",
        },
        {
          code: "2",
          name: "区-固",
        },
        {
          code: "3",
          name: "固-分",
        },
        {
          code: "4",
          name: "固",
        },
        {
          code: "5",
          name: "手机号",
        },
      ],
      invioceType: [
        {
          id: "1",
          name: "增值税专用发票",
        },
        {
          id: "2",
          name: "增值税普通发票",
        },
        {
          id: "3",
          name: "增值税电子专用发票",
        },
        {
          id: "4",
          name: "增值税电子普通发票",
        },
      ],
      billType: [
        {
          id: "1",
          name: "订单开票",
        },
        {
          id: "2",
          name: "资金开票-资金未认领",
        },
        {
          id: "3",
          name: "资金开票-资金已认领",
        },
      ],
      formValue: {
        company: "", // 账户
        page: 1, // 页码
        size: 100, // 每页显示条数
      },
      showModelThis: this.showModel,
      select: "1",
      activeOptions: [],
      activeOptions2: [],
      actionList: [],
      ruleForm1: {
        companyNo: [],
        inv_type: "",
        inv_add: "0",
        invoice_title: [],
        invoice_code: "",
        invoice_bank: "",
        invoice_bankNo: "",
        invoice_addr: "",
        inv_out: "",
        invoice_mobile: "",
        type: "",
        total: 0,
        remark: "",
      },

      rulesThis: this.rules1,
      rules1: {
        companyNo: [
          { required: true, message: "请选择申请企业", trigger: "change" },
        ],
        inv_out: [
          {
            required: true,
            message: "请选择销售方开票信息",
            trigger: "change",
          },
        ],
        inv_add: [
          { required: true, message: "请选择发票抬头类型", trigger: "change" },
        ],
        userid: [
          { required: true, message: "请选择数据源用户", trigger: "change" },
        ],
        touserid: [
          { required: true, message: "请选择数据共享用户", trigger: "change" },
        ],
        inv_type: [
          { required: true, message: "请选择发票类型", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择开票类型", trigger: "change" },
        ],
        invoice_title: [
          { required: true, message: "请选择发票抬头", trigger: "change" },
        ],
        invoice_code: [
          { required: true, validator: validateLicense, trigger: "blur" },
        ],
        invoice_bank: [
          { required: true, message: "请输入开户银行名称", trigger: "blur" },
        ],
        invoice_bankNo: [
          { required: true, message: "请输入开户银行账号", trigger: "blur" },
        ],
        invoice_addr: [
          { required: true, message: "请输入纳税登记地址", trigger: "blur" },
        ],
        invoice_mobile: [
          { required: true, validator: validatemobile, trigger: "blur" },
        ],
        total: [
          { required: false, message: "请输入发票总额", trigger: "blur" },
        ],
        remark: [{ required: false, message: "请输入备注", trigger: "blur" }],
      },

      dataForm: {
        name: "", // 业务员名字
        status: "", //
      },
      activeOptions: [],
      groupallList: [],
      multipleSelection: [],
    };
  },
  watch: {
    newTime: function (old, val) {
      if (old !== val) {
        this.initForm();
      }
    },
  },
  mounted() {
    this.initForm();
  },
  methods: {
    editRow(index) {
      this.activeIndex = index;
      this.activeItem = this.tableData[index];
      this.showGoodChangeModel = true;
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
      // this.$set(rows,index,rows[index])
    },
    goodChangeEnd(e) {
      if (e) {
        const { remark, total_fee, good_num, unit } = e;
        this.tableData[this.activeIndex].remark = remark;
        this.tableData[this.activeIndex].total_fee = total_fee;
        this.tableData[this.activeIndex].good_num = good_num;
        this.tableData[this.activeIndex].unit = unit;
      }
    },
    selectChangeMobile() {
      this.$refs.ruleForm1.validateField("invoice_mobile");
    },
    invAddChange() {
      if (this.ruleForm1.inv_add === "1") {
        this.ruleForm1.invoice_title = "";
        this.setcwRes();
        this.setform1();
      }
    },

    orderRefresh(e) {
      let arr = JSON.parse(JSON.stringify(this.tableData));
      e.forEach((v1) => {
        let fi = arr.findIndex(
          (v2) => v2.sequenceNo === v1.sequenceNo && v2.orderNo === v1.orderNo
        );
        if (fi > -1) {
          arr.splice(fi, 1);
        }
      });
      this.tableData = [].concat(arr).concat(e);
      this.tableData.forEach((v1, i1) => {
        this.$set(this.tableData, i1, v1);
      });
    },

    capitalRefresh(e) {
      let arr = JSON.parse(JSON.stringify(this.capitalTableData));
      e.forEach((v1) => {
        let fi = arr.findIndex(
          (v2) => v2.sequenceNo === v1.sequenceNo && v2.orderNo === v1.orderNo
        );
        if (fi > -1) {
          arr.splice(fi, 1);
        }
      });
      this.capitalTableData = [].concat(arr).concat(e);
      this.capitalTableData.forEach((v1, i1) => {
        this.$set(this.capitalTableData, i1, v1);
      });
    },
    // 新建/编辑/详情
    openModal(type) {
      let arr = JSON.parse(JSON.stringify(this.ruleForm1.companyNo));
      this.modelId = arr.join(",");
      if (type === 1) {
        this.showOrderModel = true;
      } else {
        this.showCapitalModel = true;
      }
    },

    closeModel() {
      console.log("closeModel!!");
    },
    async initForm() {
      this.step = 1;
      this.remark = "";
      this.exam_remark = "";
      this.loading = true;
      this.cwRes = null;
      this.disableds = this.isDetail !== "003" && this.isDetail !== "005";
      this.tableData = [];
      await this.getCompanylist();
      if (this.isDetail === "003") {
        this.title = "添加发票申请";
        this.rulesThis = this.rules1;
        await this.resetForm();
      } else {
        console.log(this.isDetail);
        if (this.isDetail == "005") {
          this.title = "发票申请详情";
          this.rulesThis = this.rules1;
        } else if (this.isDetail === "007") {
          this.title = "修改发票申请";
          this.rulesThis = {};
        }
        console.log(this.rulesThis);
        await this.resetForm();
        await this.initData();
      }
      this.loading = false;
    },

    async getCompanylist() {
      this.invoiceList = [];
      const res = await asyncRequest.companylist({
        page: 1,
        size: 30,
      });
      if (res && res.code === 0 && res.data && res.data.list) {
        this.invoiceList = res.data.list;
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.invoiceList = [];
      }
    },
    async selectChange() {
      let arr = JSON.parse(JSON.stringify(this.ruleForm1.companyNo));
      let code = arr.join(",");
      if (code === "") {
        this.cwRes = null;
        this.setform1();
      } else {
        await this.getCaiwu(code);
      }
      this.tableData = [];
      this.capitalTableData = [];
    },

    async selectChange2() {
      let arr = JSON.parse(JSON.stringify(this.ruleForm1.invoice_title));
      let code = arr.join(",");
      if (code === "") {
        this.cwRes = null;
        this.setform1();
      } else {
        let index = this.activeOptions2.findIndex(
          (v1) => v1.id + "" === code + ""
        );
        if (index !== -1) {
          this.setcwRes();
          for (let k in this.cwRes) {
            this.cwRes[k] = this.activeOptions2[index][k]
              ? this.activeOptions2[index][k] + ""
              : "";
            if (k !== "invoice_title" && k !== "companyNo") {
              this.ruleForm1[k] = this.activeOptions2[index][k]
                ? this.activeOptions2[index][k] + ""
                : "";
            }
            console.log(this.ruleForm1);
            this.setTypeM(this.ruleForm1.invoice_mobile);
            this.validateFormField();
          }
        } else {
          this.cwRes = null;
          this.setform1();
        }
      }
    },
    setform1() {
      if (this.ruleForm1.inv_add === "1") {
        this.ruleForm1.invoice_title = [];
      } else {
        this.ruleForm1.invoice_title = "";
      }

      this.ruleForm1.invoice_code = "";
      this.ruleForm1.invoice_bank = "";
      this.ruleForm1.invoice_bankNo = "";
      this.ruleForm1.invoice_addr = "";
      this.ruleForm1.invoice_mobile = "";
      this.validateFormField();
    },
    validateFormField() {
      if (this.$refs.ruleForm1) {
        this.$refs.ruleForm1.validateField("invoice_title");
        this.$refs.ruleForm1.validateField("invoice_code");
        this.$refs.ruleForm1.validateField("invoice_bank");
        this.$refs.ruleForm1.validateField("invoice_bankNo");
        this.$refs.ruleForm1.validateField("invoice_addr");
        this.$refs.ruleForm1.validateField("invoice_mobile");
      }
    },
    setcwRes() {
      this.cwRes = {
        id: "",
        companyNo: "",
        companyName: "",
        invoice_title: "",
        invoice_code: "",
        invoice_bank: "",
        invoice_bankNo: "",
        invoice_addr: "",
        invoice_mobile: "",
      };
    },
    async getCaiwu(code) {
      const res = await asyncRequest.cwlist({ companyNo: code });
      if (res && res.code === 0 && res.data) {
        let data = res.data;
        this.setcwRes();
        for (let k in this.cwRes) {
          this.cwRes[k] = data[k] ? data[k] + "" : "";
          if (k === "invoice_title" || k === "companyNo") {
            this.ruleForm1["invoice_title"] = [data["companyNo"]]
              ? [data["companyNo"]]
              : [];
          } else {
            this.ruleForm1[k] = data[k] ? data[k] + "" : "";
          }
          this.setTypeM(this.ruleForm1.invoice_mobile);
          this.validateFormField();
        }
        this.activeOptions2 = [data];
        this.ruleForm1.invoice_title = [data.id];
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.cwRes = null;
        this.$message.warning(res.message);
        this.setform1();
      }
    },
    async getCaiwu2(code) {
      const res = await asyncRequest.cwlist({ name: code });
      if (res && res.code === 0 && res.data) {
        let data = res.data;
        this.setcwRes();
        for (let k in this.cwRes) {
          this.cwRes[k] = data[k] ? data[k] + "" : "";
          if (k === "invoice_title" || k === "companyNo") {
            this.ruleForm1["invoice_title"] = [data["companyNo"]]
              ? [data["companyNo"]]
              : [];
          } else {
            this.ruleForm1[k] = data[k] ? data[k] + "" : "";
          }
          this.validateFormField();
        }
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.cwRes = null;
        this.setform1();
        this.$message.warning(res.message);
      }
    },

    async remoteMethod(query) {
      this.selectLoading = true;
      if (query !== "") {
        this.activeOptions = [];
        this.formValue.company = query;
        const res = await asyncRequest.clist(this.formValue);
        if (res && res.code === 0 && res.data && res.data.list) {
          this.activeOptions = res.data.list;
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      } else {
        this.activeOptions = [];
      }
      this.selectLoading = false;
    },

    async remoteMethod2(query) {
      this.selectLoading2 = true;
      if (query !== "") {
        this.activeOptions2 = [];
        const res = await asyncRequest.invoicelist({ name: query });
        if (res && res.code === 0 && res.data) {
          this.activeOptions2 = res.data;
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      } else {
        this.activeOptions2 = [];
      }
      this.selectLoading2 = false;
    },
    async initData() {
      const res = await asyncRequest.detail({ id: this.id });
      if (
        res &&
        res.code === 0 &&
        res.data &&
        res.data.customer &&
        res.data.customer.companyNo
      ) {
        const {
          invoice_title,
          invoice_code,
          invoice_bank,
          invoice_bankNo,
          invoice_addr,
          invoice_mobile,
          inv_type,
          type_check,
          customer,
          inv_value,
          remark,
          inv_add,
          exam_remark,
          order,
          trade,
          inv_out,
        } = res.data;
        const { companyNo } = customer;
        // const data = res.data;
        // const customer = res.data.customer;

        this.cwRes = {
          id: "0",
          companyNo: "0",
          companyName: "0",
          invoice_title: invoice_title,
          invoice_code: invoice_code,
          invoice_bank: invoice_bank,
          invoice_bankNo: invoice_bankNo,
          invoice_addr: invoice_addr,
          invoice_mobile: invoice_mobile,
        };
        this.ruleForm1 = {
          companyNo: [companyNo],

          inv_type: inv_type ? parseInt(inv_type) + "" : "",
          type: type_check ? parseInt(type_check) + "" : "",
          total: inv_value,
          remark: remark,
          inv_add: inv_add,
          inv_out: inv_out,
          invoice_title: [invoice_title],
          invoice_code: invoice_code,
          invoice_bank: invoice_bank,
          invoice_bankNo: invoice_bankNo,
          invoice_addr: invoice_addr,
          invoice_mobile: invoice_mobile,
        };
        this.activeOptions = [customer];
        this.remark = remark;
        this.exam_remark = exam_remark;
        this.setTypeM(invoice_mobile);
        // console.log(this.ruleForm1);
        if (!this.disableds) {
          this.changetype(this.ruleForm1.type);
        }
        let good =
          order && order.good && order.good.length > 0
            ? JSON.parse(JSON.stringify(order.good))
            : [];
        good.map((v1) => {
          v1.sequenceNo = v1.goodNo;
          v1.goodname = v1.good_name;
          v1.over_num = parseInt(v1.num) - parseInt(v1.inv_num);
          return v1;
        });
        this.tableData = good;
        this.capitalTableData = trade;
        this.capitalTableData.forEach((v1, i1) => {
          v1.customer = v1.companyName;
          this.$set(this.capitalTableData, i1, v1);
        });
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
      console.log(this.ruleForm1);
    },
    changetype(val) {
      if (this.rulesThis && this.rulesThis.total && this.rulesThis.remark) {
        if (val === 1) {
          this.rulesThis.total[0].required = false;
          this.rulesThis.remark[0].required = false;
        } else {
          this.rulesThis.total[0].required = true;
          this.rulesThis.remark[0].required = true;
        }
      }
    },
    setTypeM(mobile) {
      if (isMobile(mobile)) {
        this.schange = "5";
      } else if (isqzf(mobile)) {
        this.schange = "1";
      } else if (isqz(mobile)) {
        this.schange = "2";
      } else if (iszf(mobile)) {
        this.schange = "3";
      } else {
        this.schange = "4";
      }
      console.log(this.schange);
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm1) {
          this.$refs.ruleForm1.resetFields();
          this.$refs.ruleForm1.clearValidate();
          this.cwRes = null;
          this.ruleForm1 = {
            companyNo: [],
            inv_type: "",
            type: "",
            inv_add: "0",
            total: 0,
            remark: "",
            invoice_title: [],
            invoice_code: "",
            invoice_bank: "",
            invoice_bankNo: "",
            invoice_addr: "",
            invoice_mobile: "",
          };
        }
      });
    },
    async submitForm1() {
      await this.$refs.ruleForm1.validate(async (valid) => {
        if (valid) {
          if (this.ruleForm1.type === "2") {
            await this.mAddOrUpdate();
          } else {
            this.step = 2;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //认领资金开票
    async submitForm2() {
      if (!this.loading) {
        // remark;

        if (this.capitalTableData.length === 0) {
          this.$message.warning("请选择资金！");
          return;
        }
        const list = [];
        this.capitalTableData.forEach((v1) => {
          list.push(v1.traNo);
        });
        const model = await this.setInputForm(1);
        model.traNo = list;
        delete model["total"];
        delete model["good"];

        console.log(model);
        this.loading = true;
        let res = {};
        if (this.id === "add") {
          delete model["invNo"];
          res = await asyncRequest.receiptbytrade(model);
        } else {
          delete model["traNo"];
          delete model["inv_type"];
          res = await asyncRequest.editbytrade(model);
        }
        this.loading = false;
        if (res && res.code === 0) {
          const title = this.id === "add" ? "添加成功" : "修改成功";
          this.$notify.success({
            title,
            message: "",
          });
          this.$emit("refreshAll");
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      }
    },

    async mAddOrUpdate() {
      if (!this.loading) {
        this.loading = true;
        const model = await this.setInputForm();
        delete model["traNo"];
        delete model["good"];
        console.log(model);
        let res = {};
        if (this.id === "add") {
          delete model["invNo"];
          res = await asyncRequest.madd(model);
        } else {
          res = await asyncRequest.mupdate(model);
        }
        this.loading = false;
        if (res && res.code === 0) {
          const title = this.id === "add" ? "添加成功" : "修改成功";
          this.$notify.success({
            title,
            message: "",
          });
          this.$emit("refreshAll");
          //   this.showModelThis = false;
          // 刷新
          //   this.$emit("refresh");
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      }
    },

    //订单开票
    async submitForm() {
      if (!this.loading) {
        if (this.tableData.length === 0) {
          this.$message.warning("请选择确认单商品");
          return;
        }
        const list = JSON.parse(JSON.stringify(this.tableData));
        let isok = true;
        let isremark = true;
        const model = await this.setInputForm(1);
        delete model["traNo"];
        delete model["total"];
        console.log(model);
        list.forEach((v1) => {
          if (v1.good_num === 0) {
            isok = false;
          }
          if (v1.total_fee === 0) {
            isok = false;
          }
          console.log(v1.unit);
          if (v1.unit === "" || v1.unit === undefined || v1.unit === null) {
            isok = false;
          }
          let str = v1.remark.replace(/\s*/g, "");
          if (str === "") {
            isremark = false;
          }
          let item = {
            sequenceNo: v1.sequenceNo,
            remark: str,
            total_fee: v1.total_fee,
            num: v1.good_num,
            unit: v1.unit,
          };
          model.good.push(item);
        });
        if (!isok) {
          this.$message.error("商品数量/商品总额不能为0,商品单位不能为空！");
          return;
        }
        if (!isremark) {
          this.$message.error("开票商品名不能为空！");
          return;
        }
        this.loading = true;
        let res = {};
        if (this.id === "add") {
          delete model["invNo"];
          res = await asyncRequest.oadd(model);
        } else {
          res = await asyncRequest.oupdate(model);
        }
        this.loading = false;
        if (res && res.code === 0) {
          const title = this.id === "add" ? "添加成功" : "修改成功";
          this.$notify.success({
            title,
            message: "",
          });
          this.$emit("refreshAll");
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(res.message);
        }
      }
    },
    //解构接口入参字段重新组合
    async setInputForm(type) {
      const {
        inv_add,
        companyNo,
        inv_type,
        inv_out,
        total,
        remark,
        invoice_title,
        invoice_code,
        invoice_bank,
        invoice_bankNo,
        invoice_addr,
        invoice_mobile,
      } = JSON.parse(JSON.stringify(this.ruleForm1));

      const model = {
        invNo: this.invNo,
        traNo: [],
        inv_add: inv_add,
        companyNo: companyNo.join(), //企业
        inv_type: inv_type + "", //发票类型
        inv_out: inv_out,
        total: total + "", //金额
        remark: type ? this.remark : remark + "",
        invoice_title:
          inv_add == "0" ? this.cwRes.invoice_title : invoice_title,
        invoice_code: invoice_code,
        good: [],
        invoice_bank: invoice_bank,
        invoice_bankNo: invoice_bankNo,
        invoice_addr: invoice_addr,
        invoice_mobile: invoice_mobile,
      };
      return model;
    },
  },
};
</script>

   <style lang="scss" scoped>
.invoiceApply {
  .fp-title {
    float: left;
    width: 100px;
    text-align: right;
    line-height: 46px;
    box-sizing: border-box;
    color: #99a9bf;
    padding: 0 10px 0 0;

    font-size: 14px;
  }
  .fp-name {
    width: calc(100% - 125px);
    font-size: 14px;
    float: left;
    padding: 10px 0;
    line-height: 26px;
  }
}
</style>
