<template>
  <el-dialog
    center
    :title="title"
    :visible="_visible"
    @close="handleClose"
    :close-on-click-modal="false"
    width="1024px"
  >
    <el-form ref="formRef" label-width="80px" size="mini" :model="ruleForm" :rules="rules">
        <el-input
          v-if="!ruleForm.childCode"
          style="cursor: pointer"
          placeholder="选择子商品"
          v-model="ruleForm.childCode"
          @focus="pVisible = true"
        />

        <div v-else style="display:flex">
          <show-data-table :columns="basicColumns" :sitem="sitem" border>
            <template slot="packing_spec">
              <el-tag
                size="mini"
              >{{ ( options6.find(({id}) => id === sitem.supply_area) || {}).name || '--' }}</el-tag>
            </template>

            <template slot="is_auth">
              <el-tag
                size="mini"
              >{{ ( options3.find(({id}) => id === sitem.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="sitem.good_info_img"
                  :preview-src-list="[sitem.good_info_img]"
                />
              </div>
            </template>

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

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

            <template slot="good_name">
              <img
                v-if="sitem.good_thumb_img"
                v-viewer
                style="width: 23px; height: 23px; margin: 0 5px 0 0"
                class="fl"
                :src="sitem.good_thumb_img"
                alt
              />
              <span>{{ sitem.good_name }}</span>
              <span v-for="(si, i) in sitem.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>{{ sitem.spuCode }}</span>
                  </li>
                </ul>
                <i slot="reference" class="el-icon-warning-outline fr" />
              </el-popover>
            </template>

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

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

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

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

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

      <!-- <el-form-item label="组合比例" prop="child_num">
        <digital-input
          :disabled="this.type === 'view'"
          :values="ruleForm.child_num"
          :placeholder="'组合比例'"
          :min="0"
          :max="100"
          :position="'right'"
          :precision="0"
          :controls="false"
          size="mini"
          :append="''"
          @reschange="child_numChange"
        />
      </el-form-item>-->

      <el-form-item v-if="type !== 'view'">
        <div style="display:flex;justify-content:flex-end">
          <el-button type="primary" @click="submit">保 存</el-button>
        </div>
      </el-form-item>
    </el-form>

    <product-list-modal :visible.sync="pVisible" @selected="handleProductChange" />
  </el-dialog>
</template>

<script>
import ProductListModal from "./productListModal.vue";
import asyncRequest from "@/apis/service/goodStore/goodsCost";
import privateField from "@/mixins/privateField";

import {
  basicColumns,
  packingColumns,
  sendColumns,
  imageColumns,
  ladderColumns,
  options3,
  options6
} from "./../columns";

export default {
  name: "ProductModal",
  props: ["visible", "editItem", "editIndex", "type"],
  components: { ProductListModal },
  mixins: [privateField],
  computed: {
    _visible: {
      get() {
        return this.visible;
      },
      set(nV) {
        this.$emit("update:visible", nV);
      }
    },
    title() {
      const mapTitle = {
        add: "添加子商品",
        edit: "编辑子商品",
        view: "查看子商品"
      };
      return mapTitle[this.type];
    }
  },
  watch: {
    editItem: {
      handler(v) {
        console.log(v);
        if (!v) return;
        const { childCode, goodType, child_name, child_num } = v;
        this.handleProductChange(childCode);
        this.ruleForm = {
          childCode,
          goodType,
          child_name,
          child_num
        };
      },
      deep: true
    }
  },
  data() {
    return {
      basicColumns,
      packingColumns,
      sendColumns,
      imageColumns,
      ladderColumns,
      options3,
      options6,
      newTime: "",
      loading: false,
      pVisible: false,
      ruleForm: {
        childCode: "",
        goodType: "",
        child_name: "",
        child_num: ""
      },
      origin_place: "",
      delivery_place: "",
      sitem: null,
      rules: {
        childCode: [
          {
            required: true,
            trigger: "change",
            message: "请选择子商品"
          }
        ],
        child_num: [
          {
            required: true,
            trigger: "change",
            message: "请输入组合比例"
          }
        ]
      }
    };
  },
  methods: {
    handleClose() {
      this.ruleForm = {
        childCode: "",
        goodType: "",
        child_name: "",
        child_num: ""
      };
      this._visible = false;
    },
    child_numChange(child_num) {
      this.ruleForm.child_num = child_num;
    },
    resetProduct() {
      this.ruleForm.childCode = "";
      this.ruleForm.goodType = "";
      this.ruleForm.child_name = "";
      this.sitem = null;
    },
    getNewTime() {
      this.newTime = new Date().valueOf();
    },
    async submit() {
      try {
        await this.$refs.formRef.validate();
        console.log(this.editIndex);
        this.$emit("save", this.ruleForm, this.editIndex);
        this._visible = false;
      } catch (e) {
        console.log(e);
      }
    },
    async getArea(prop = "delivery_place") {
      const chunks = this.sitem[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]);
      this[prop] = [province, city, area].map(({ name }) => name).join("_");
    },
    async handleProductChange(spuCode) {
      this.loading = true;

      const { code, message, data } = await asyncRequest.detail({
        spuCode
      });

      this.loading = false;
      if (code === 0) {
        this.sitem = JSON.parse(JSON.stringify(data));

        const { good_name, good_type, spuCode } = this.sitem;
        this.ruleForm.childCode = spuCode;
        this.ruleForm.goodType = good_type;
        this.ruleForm.child_name = good_name;

        await this.getArea("delivery_place");
        await this.getArea("origin_place");

        this.getNewTime();

        this.$nextTick(() => this.$refs.formRef.validateField("childCode"));
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    }
  }
};
</script>
