<template>
  <div class="select-invoice-products">
    <div v-if="existISPSignPays">
      <select-invoice-products-item
        v-for="(item, index) in ispSignPays"
        :key="index"
        :bind="item"
        class="mb16"
        @init="handleSelectItemInit"
        @change="handleSelectItemChange"
      ></select-invoice-products-item>
    </div>

    <div v-else>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input disabled v-model="vmValueCopy"></el-input>
        </el-col>

        <el-col :span="20">
          <el-button
            type="primary"
            icon="el-icon-plus"
            :loading="loadingISPSignPays"
            @click="handleGetISPSignPay"
          >
            立即添加
          </el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import SelectInvoiceProductsItem from "./select-invoice-products-item.vue";
import CommodityService from "@/api/commodity";

export default {
  name: "SelectInvoiceProducts",
  components: {
    SelectInvoiceProductsItem,
  },
  model: {
    prop: "vmValue",
    event: "changeVMValue",
  },
  props: {
    vmValue: String,
  },
  data() {
    return {
      /**
       * 签约企业列表；
       */
      ispSignPays: null,
      loadingISPSignPays: false,

      // 存放签约企业与开票商品信息；
      result: null,

      vmValueCopy: this.vmValue,
    };
  },
  watch: {
    vmValue(newVal) {
      this.vmValueCopy = newVal;
    },
  },
  computed: {
    /**
     * 是否存在签约企业；
     */
    existISPSignPays() {
      const list = this.ispSignPays || [];
      return list.length > 0;
    },
  },
  methods: {
    /**
     * 获取签约企业列表；
     */
    handleGetISPSignPay() {
      const _this = this;
      _this.loadingISPSignPays = true;
      CommodityService.findISPSignPay({
        pageSize: 1000,
      })
        .then((val) => {
          if (val.data) {
            _this.ispSignPays = val.data.records || [];

            // 处理对应开票商品外部传值；
            // 加载签约企业时，同步已处在的选择项；
          } else {
            _this.$message.error("data is null.");
          }
        })
        .catch((err) => {
          _this.$message.error(err);
        })
        .finally(() => {
          _this.loadingISPSignPays = false;
        });
    },

    handleSelectItemInit(item) {
      this.updateResult(item);
    },

    handleSelectItemChange(item) {
      this.updateResult(item);
    },

    updateResult(item) {
      if (!(this.result instanceof Object)) {
        this.result = {};
      }
      this.result[item.infoId] = item.invoiceProductId;
      this.$emit("changeVMValue", JSON.stringify(this.result));
    },

    /**
     * 重置；
     */
    reset() {
      this.ispSignPays = null;
      this.result = null;
      this.$emit("changeVMValue", "无");
    },

    /**
     * 设置信息；
     */
    setInfo(jsonText) {
      if (jsonText === "无") {
        this.reset();
        return;
      }

      try {
        this.result = JSON.parse(jsonText);
        this.$emit("changeVMValue", JSON.stringify(this.result));
      } catch (error) {
        console.error("invoiceProductId JSON.parse error");

        // 结束，当值不存在；
        this.reset();
        return false;
      }

      const _this = this;
      _this.loadingISPSignPays = true;
      CommodityService.findISPSignPay({
        pageSize: 1000,
      })
        .then((val) => {
          if (val.data) {
            const records = val.data.records || [];
            // 处理对应开票商品外部传值；
            // 加载签约企业时，同步已处在的选择项；
            records.forEach((item) => {
              const infoIdValue = _this.result[item.infoId];
              if (infoIdValue) {
                item["invoiceProductId"] = infoIdValue;
              }
            });

            _this.ispSignPays = records;
          } else {
            _this.$message.error("data is null.");
          }
        })
        .catch((err) => {
          _this.$message.error(err);
        })
        .finally(() => {
          _this.loadingISPSignPays = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.select-invoice-products {
  .mb16 {
    margin-bottom: 24px;
  }
}
</style>
