<template>
  <el-form
    ref="ruleForm"
    v-loading="loading.full"
    label-width="90px"
    size="mini"
    :model="ruleForm"
    :rules="rules"
  >
    <el-form-item v-loading="loading.product" label="组合商品" prop="spuCode">
      <el-input v-if="!productinfo" placeholder="选择组合商品" @focus="pVisible = true" />

      <el-collapse-transition>
        <div v-if="productinfo" key="product" style="display:flex">
          <show-goods-data-table
            border
            type="1"
            v-if="newTime !== ''"
            :iscgd="true"
            :newTime="newTime"
            :spucode="productinfo.spuCode"
            :isStockInfo="true"
          />

          <el-tooltip v-if="type !== 'view'" content="重新选择组合商品" placement="top">
            <i
              class="el-icon-circle-close"
              style="cursor:pointer;font-size:18px;margin-left:10px"
              @click="resetProduct"
            />
          </el-tooltip>
        </div>
      </el-collapse-transition>
    </el-form-item>

    <el-form-item v-loading="loading.stock" label="所在仓库" prop="wsm_code">
      <el-input
        v-if="!stockinfo"
        :disabled="!productinfo"
        placeholder="选择所在仓库"
        @focus="sVisible = true"
      />

      <el-collapse-transition>
        <div v-if="stockinfo" key="stock" style="display:flex">
          <show-data-table border :columns="stockColumns" :sitem="stockinfo" />
          <el-tooltip content="重新选择仓库" placement="top">
            <i
              class="el-icon-circle-close"
              style="cursor:pointer;font-size:18px;margin-left:10px"
              @click="resetStock"
            />
          </el-tooltip>
        </div>
      </el-collapse-transition>
    </el-form-item>

    <el-row>
      <el-col :span="24">
        <el-form-item label="添加库存数" prop="stock_num" label-width="110px">
          <digital-input
            :values="ruleForm.stock_num"
            :placeholder="'添加库存数'"
            :min="0"
            :max="100000000000"
            :position="'right'"
            :precision="0"
            :size="'mini'"
            :controls="false"
            :append="''"
            @reschange="number_change($event, 'stock_num')"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="子商品库存情况" label-width="110px">
      <el-table :data="productinfo ? productinfo.combind_list : []" size="mini" border>
        <el-table-column label="子商品成本编号" prop="childCode" min-width="160px" />
        <el-table-column label="子商品名称" prop="child_name" min-width="180px" show-overflow-tooltip />
        <el-table-column label="组合比例" prop="child_num" />
        <el-table-column label="本次添加库存数">
          <template slot-scope="{ row }">{{ calcStockNum(row) }}</template>
        </el-table-column>
        <el-table-column label="剩余可用可用库存数">
          <template slot-scope="{ row }">{{ row.usable_stock || 0}}</template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <div class="flex-end" style="width:100%;display:flex;justify-content:flex-end">
        <el-button size="mini" type="primary" @click="submit">保存</el-button>
      </div>
    </el-form-item>

    <stock-modal
      :visible.sync="sVisible"
      :supplierNo="productinfo ? productinfo.supplierNo :''"
      @selected="handleStockSelected"
    />
    <product-modal :visible.sync="pVisible" @selected="handleProductSelected" />
  </el-form>
</template>

<script>
import StockModal from "./stockModal.vue";
import ProductModal from "./productModal.vue";
import privateField from "@/mixins/privateField";
import asyncRequest from "@/apis/service/sellOut/combindAdd";
import { stockColumns, productColumns } from "./columnsForm";
import { add_sum, isnumber, accMul } from "@/utils/validate";

const validateNum = (_, value, callback) => {
  if (value === "") {
    callback(new Error("添加库存数不能为空！"));
  } else {
    const num = parseInt(value + "");
    console.log(num);
    if (!isnumber(value)) {
      callback(new Error("添加库存数必须是整数！"));
    } else if (num === NaN) {
      callback(new Error("添加库存数必须是整数！"));
    } else if (num === 0) {
      callback(new Error("添加库存数不能为零！"));
    } else {
      callback();
    }
  }
};

export default {
  name: "BaseForm",
  components: { StockModal, ProductModal },
  mixins: [privateField],
  data() {
    return {
      stockColumns,
      productColumns,
      sVisible: false,
      pVisible: false,
      stockinfo: null,
      productinfo: null,
      loading: {
        product: false,
        stock: false,
        full: false
      },
      ruleForm: {
        spuCode: "",
        wsm_code: "",
        stock_num: 0,
        usable_stock: 0
      },
      options6: [
        { id: "1", name: "全国" },
        { id: "2", name: "全国除偏远" }
      ],
      options3: [
        { id: "0", name: "无销售权限" },
        { id: "1", name: "有销售权限" }
      ],
      rules: {
        spuCode: [
          { required: true, trigger: "change", message: "请选择组合商品" }
        ],
        wsm_code: [
          { required: true, trigger: "change", message: "请选择所在仓库" }
        ],
        stock_num: [
          { required: true, trigger: "change", validator: validateNum }
        ]
      }
    };
  },
  methods: {
    async submit() {
      try {
        await this.$refs.ruleForm.validate();
        const { usable_stock, ...params } = this.ruleForm;
        for (let item of this.productinfo.combind_list) {
          const { child_num, usable_stock, child_name } = item;
          if (
            parseInt(accMul(this.ruleForm.stock_num, child_num)) > usable_stock
          ) {
            this.$message.warning(
              `子商品  ${child_name}  添加库存数不能超过可用库存数`
            );
            return;
          }
        }

        this.loading.full = true;
        const { code, message } = await asyncRequest.add({
          ...params,
          flag: "1"
        });
        this.loading.full = false;

        if (Number(code) === 0) {
          this.$router.push("/sellOut/combinedAdd");
          return;
        } else if (code === 1004) {
          this.$message.warning(message);
        }
      } catch (e) {
        console.log(e);
      }
    },
    number_change(e, key) {
      this.ruleForm[key] = e;
      this.$nextTick(() => {
        this.$refs.ruleForm && this.$refs.ruleForm.validateField(key);
      });
    },
    resetStock() {
      this.stockinfo = null;
      this.ruleForm.wsm_code = "";
    },
    resetProduct() {
      this.productinfo = null;
      this.stockinfo = null;
      this.ruleForm.wsm_code = "";
      this.ruleForm.spuCode = "";
    },
    calcStockNum(row) {
      const { child_num } = row;
      return parseInt(accMul(this.ruleForm.stock_num, child_num));
    },
    async handleStockSelected(evt) {
      const { id } = evt;
      this.loading.stock = true;
      const { code, data } = await asyncRequest.stockinfo({ id });
      if (code !== 0) return;
      const { addr_code, addrs_code } = data;

      const { city_code: sourceCodeL2, area_code: sourceCodeL3 } = addr_code;
      const { city_code: targetCodeL2, area_code: targetCodeL3 } = addrs_code;

      const { code: _co1, data: _d1 } = await asyncRequest.addrquery({
        code: sourceCodeL2,
        level: 3
      });

      const { code: _co2, data: _d2 } = await asyncRequest.addrquery({
        code: targetCodeL2,
        level: 3
      });

      this.loading.stock = false;

      if (_co1 === 0) {
        const d1 = _d1.find(item => item.code === sourceCodeL3);
        const { area: _a1, city: _c1, province: _p1 } = (d1 || {}).info || {};
        data.source = [_p1, _c1, _a1].map(({ name }) => name).join("");
      }

      if (_co2 === 0) {
        const d2 = _d2.find(item => item.code === targetCodeL3);
        const { area: _a2, city: _c2, province: _p2 } = (d2 || {}).info || {};
        data.target = [_p2, _c2, _a2].map(({ name }) => name).join("");
      }

      this.stockinfo = data;
      this.ruleForm.wsm_code = data.wsm_code;
    },
    async getArea(prop = "delivery_place") {
      const chunks = this.productinfo[prop].split(",");
      let { data: province } = await asyncRequest.province();
      province = province.find(
        ({ province_code }) => province_code === chunks[0]
      );
      let { data: city } = await asyncRequest.city({ code: chunks[0] });
      city = city.find(({ city_code }) => city_code === chunks[1]);
      let { data: area } = await asyncRequest.area({ code: chunks[1] });
      area = area.find(({ area_code }) => area_code === chunks[2]) || {};
      return [province, city, area].map(({ name }) => name).join("");
    },
    async handleProductSelected(spuCode) {
      this.loading.product = true;
      const { code, data } = await asyncRequest.productinfo({ spuCode });
      if (code !== 0) return;
      this.productinfo = data;

      (data.combind_list || []).forEach(item => {
        this.ruleForm.usable_stock = add_sum(
          this.ruleForm.usable_stock || 0,
          item.usable_stock || 0
        );
      });
      this.ruleForm.spuCode = spuCode;
      this.delivery_place = await this.getArea("delivery_place");
      this.origin_place = await this.getArea("origin_place");
      this.loading.product = false;
    }
  }
};
</script>
