<template>
  <show-data-table border :columns="stockColumns" :sitem="stockinfo" v-loading="loading" />
</template>

<script>
import asyncRequest from "@/apis/components/details";
import { stockColumns } from "./columns";
export default {
  name: "StockDetail",
  data() {
    return {
      stockColumns,
      loading: false,
      stockinfo: {}
    };
  },
  watch: {
    wsm_code: {
      handler() {
        this.initData();
      },
      immediate: true
    }
  },
  methods: {
    async initData(wsm_code) {
      this.loading = true;
      const { code, data } = await asyncRequest.stockinfo({ wsm_code });
      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 = 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;
    }
  }
};
</script>
