<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" />

      <div v-else key="product" style="display:flex">
        <show-goods-data-table
          border
           v-if="newTime !== ''"
           type="1"
           :iscgd="true"
           :newTime="newTime"
           :spucode="productinfo.spuCode"
           :isStockInfo="true"
         />
        
        <!-- <show-data-table border :columns="productColumns" :sitem="productinfo">
          <template slot="packing_spec">
            <el-tag
              size="mini"
            >{{ ( options6.find(({id}) => id === productinfo.supply_area) || {}).name || '--' }}</el-tag>
          </template>

          <template slot="is_auth">
            <el-tag
              size="mini"
            >{{ ( options3.find(({id}) => id === productinfo.is_auth) || {}).name || '--' }}</el-tag>
          </template>

          <template slot="good_info_img">
            <div style="max-height: 24px; overflow: hidden">
              <el-image
                style="height: 24px; width: 24px"
                :src="productinfo.good_info_img"
                :preview-src-list="[productinfo.good_info_img]"
              />
            </div>
          </template>

          <template slot="cat_info">
            {{
            productinfo.cat_info
            ? productinfo.cat_info.map(({ name }) => name).join("_")
            : "--"
            }}
          </template>

          <template slot="is_combind">
            {{
            String(productinfo.is_combind) === '1' ? '组合商品' : '非组合商品'
            }}
          </template>

          <template slot="good_name">
            <img
              v-if="productinfo.good_thumb_img"
              v-viewer
              style="width: 23px; height: 23px; margin: 0 5px 0 0"
              class="fl"
              :src="productinfo.good_thumb_img"
              alt
            />
            <span>{{ productinfo.good_name }}</span>
            <span v-for="(si, i) in productinfo.speclist" :key="si.spec_id + i">
              <span v-if="i !== 0">-</span>
              <span v-else>_</span>
              <span>{{ si.spec_name }}[{{ si.spec_value }}]</span>
            </span>
            <el-popover placement="top" width="300" trigger="hover">
              <ul>
                <li v-if="newTime !== '' && isDisplayPrivateField('1')">
                  <span>商品成本编号：</span>
                  <span>{{ productinfo.spuCode }}</span>
                </li>
              </ul>
              <i slot="reference" class="el-icon-warning-outline fr" />
            </el-popover>
          </template>

          <template slot="noble">
            <span v-if="productinfo.noble_metal">
              {{ productinfo.noble_weight ? productinfo.noble_weight : "0" }}g-{{
              productinfo.noble_name
              }}-{{ productinfo.gold_price ? productinfo.gold_price : "0" }}元/g-{{
              productinfo.is_gold_price + "" === "0" ? "不" : ""
              }}启用实时金价-{{ productinfo.is_diff + "" === "1" ? "有" : "无" }}工差-{{
              productinfo.config
              }}-{{ productinfo.other_config }}
            </span>
          </template>

          <template slot="weight">{{ productinfo.weight }}g</template>
          <template slot="tax">{{ productinfo.tax }}%</template>
          <template slot="is_stock">{{ String(productinfo.is_stock) === "0" ? "非库存品" : "库存品" }}</template>
          <template
            slot="is_exclusive"
          >{{ String(productinfo.is_exclusive) === "0" ? "非泰康" : "泰康" }}</template>
          <template slot="noble_weight">{{ productinfo.noble_weight }}g</template>
          <template slot="is_gold_price">
            {{
            String(productinfo.is_gold_price) === "1" ? "是" : "否"
            }}
          </template>
          <template slot="is_diff">
            {{
            String(productinfo.is_diff) === "1" ? "有公差" : "无工差"
            }}
          </template>

          <template slot="packing_weight">{{ productinfo.packing_weight }}g</template>

          <template slot="delivery_day">{{ productinfo.delivery_day }}天</template>
          <template slot="lead_time">{{ productinfo.lead_time }}天</template>
          <template slot="sample_day">{{ productinfo.sample_day }}天</template>
          <template slot="delivery_place">{{ delivery_place }}</template>
          <template slot="origin_place">{{ origin_place }}</template>
        </show-data-table> -->

        <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-form-item>

    <el-form-item label="所在仓库" prop="wsm_code" v-if="productinfo">
      <el-table class="stock_table" row-key="id" ref="table" :data="productinfo.wsm_list" border size="mini" @select="handleSelection">
        <el-table-column type="selection" width="40px">
          <template slot="header">
            <span></span>
          </template>
        </el-table-column>
        <el-table-column label="仓库名称" prop="name" />
        <el-table-column label="仓库编码" prop="wsm_code" />
        <el-table-column label="可用库存" prop="usable_stock" />
      </el-table>
    </el-form-item>

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

      <el-col :span="12">
        <el-form-item label="可解除库存数" prop="unstockTotal" label-width="110px">
          <el-input placeholder="可解除库存数" v-model="ruleForm.usable_stock" disabled />
        </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 }">{{ row.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" @selected="handleStockSelected" />
    <product-modal :visible.sync="pVisible" @selected="handleProductSelected" />
  </el-form>
</template>

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

const validateNum = (rule, 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 {
      detailColumns,
      stockColumns,
      productColumns,
      sVisible: false,
      pVisible: false,
      stockinfo: null,
      productinfo: null,
      loading: {
        product: false,
        stock: false,
        full: false
      },
      origin_place:"",
      delivery_place:"",
      ruleForm: {
        spuCode: "",
        wsm_code: "",
        stock_num: 0,
        usable_stock: 0
      },
      selected: [],
      options6: [
        { id: "1", name: "全国" },
        { id: "2", name: "全国除偏远" }
      ],
      options3: [
        { id: "0", name: "无销售权限" },
        { id: "1", name: "有销售权限" }
      ],
      statusOptions: [
        { id: "1", label: "待审核" },
        { id: "2", label: "审核通过" },
        { id: "3", label: "审核驳回" }
      ],
      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;

        this.loading.full = true;
        const { code, message } = await asyncRequest.add({
          ...params,
          wsm_code:this.productinfo.wsm_list[0].wsm_code,
          flag: "0"
        });
        this.loading.full = false;

        if (Number(code) === 0) {
          this.$router.push("/sellOut/combinedRemove");
          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);
      });
    },
    handleSelection(selection, row){
      // this.selected = list
      this.$refs.table.clearSelection()
      
      if(selection.length === 0){
        return
      }

      this.$refs.table.toggleRowSelection(row, true)
      const { wsm_code = "" , usable_stock = 0} = row
      this.ruleForm.wsm_code = wsm_code
      this.ruleForm.usable_stock = usable_stock;
      this.$refs.ruleForm.validate("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("");
    },
    resetProduct() {
      this.productinfo = null;
      this.ruleForm.spuCode = "";
      // this.ruleForm.wsm_code = data.wsm_code;
    },
    async handleProductSelected(spuCode) {
      this.loading.product = true;
      const { code, data } = await asyncRequest.productinfo({ spuCode });

      if (code !== 0) return;
      this.productinfo = data;
      this.ruleForm.spuCode = data.spuCode;
      // this.ruleForm.wsm_code = data.wsm_code;
      this.loading.product = false;

      this.delivery_place = await this.getArea("delivery_place");
      this.origin_place = await this.getArea("origin_place");
    }
  }
};
</script>


<style scoped lang="scss">
.stock_table{
  /deep/ thead {
    .el-table-column--selection{
      .cell{
        display: none;
      }
    }
  }
}
</style>
