<template>
  <p-card title="商品货位限定策略">
    <template v-slot:extra>
      <p-button type="primary" style="margin-right: 20px" @click="switchSearch">{{
        $lang(isHideSearch ? "显示" : "隐藏")
      }}</p-button>
      <p-button type="primary" @click="addItem">{{ $lang("新增") }}</p-button>
    </template>
    <p-grid-form v-show="!isHideSearch" ref="form" style="margin-bottom: 20px" :items="searchItems" />
    <p-table
      v-if="cols"
      ref="table"
      bordered
      auto-width
      :remote-url="remoteUrl"
      row-key="stItemLocatorHId"
      :columns="cols"
      :data-source.sync="list"
      :rowSelectType="false"
      :hasRowCount="false"
      :colorTransformRow="false"
      :autoLoad="false"
      :scroll="{ x: true, y: 260 }"
      :remoteParams="remoteParams"
      :doneBefore="doneBefore"
      :done="handleQueryItems"
      @clickRow="clickRow"
    >
      <template v-slot:operation="text, record">
        <span class="btn" @click="editorItem(record)">编辑</span>
        <span class="btn" @click="delItem(record)">删除</span>
      </template>
    </p-table>

    <a-divider />

    <a-row>
      <a-col :span="16" style="min-height: 200px">
        <logic-area :stItemLocatorHId="clickStItemLocatorHId" />
      </a-col>
      <a-col :span="8" style="padding-left: 40px; min-height: 200px">
        <algorithm :stItemLocatorHId="clickStItemLocatorHId" />
      </a-col>
    </a-row>

    <editor-modal v-model="visible" :pkId="pkId" @ok="reloadTable" />
  </p-card>
</template>
<script>
import { upcloud_base_common } from "@/config/serviceSettings";
import logicArea from "./components/logicArea";
import algorithm from "./components/algorithm";
import EditorModal from "./components/editor-modal";
import { searchItems } from "./config/searchItems";
import { cols1 } from "./config/columns";
import { delItems, queryItemInfos } from "./api";
import { forSelectText } from "../../utils";
import { setCargoOwner } from "@/views/kzyWMS/utils/setCargoOwner";
import { upcloud_base_wh_control } from "@/config/serviceSettings";
import { axios } from "@/utils/request";

const GetBilltype = () => {
  return axios.post(upcloud_base_common + "/dict/listbytype?dicttypeCodes=oms_asn_bill_type");
};
export default {
  components: {
    "editor-modal": EditorModal,
    "logic-area": logicArea,
    algorithm: algorithm,
  },
  mixins: [setCargoOwner],
  data() {
    return {
      BilltypeOp: {},
      remoteUrl: { url: upcloud_base_wh_control + "/item-locator/v1/head/page" },
      isHideSearch: false,
      searchItems: searchItems(this),
      cols: null,
      remoteParams: {},
      list: [],
      visible: false,
      pkId: null,
      clickStItemLocatorHId: null,
    };
  },

  created() {
    forSelectText([cols1]).then((arr) => {
      this.cols = arr[0];
    });
  },

  async mounted() {
    let warehouse = this.$store.state.user.warehouse;
    console.log(warehouse);
    if (Object.keys(warehouse).length > 0) {
      this.$refs.form.form.setFieldsValue(warehouse);
    }
    // let res=await getAuthByUser()
    // console.log(res)
    // if(res.success){
    //      this.$refs.form.form.setFieldsValue({
    //          cargoOwnerCode: res.data.list[0].companyCode,
    //         cargoOwnerId: res.data.list[0].companyId,
    //         cargoOwnerName: res.data.list[0].companyName,

    //      })
    // }

    try {
      let res = await GetBilltype();
      if (res.success) {
        console.log(res);
        res.data = res.data.filter((_) => _.isEnable);
        console.log(res);
        // this.BilltypeOp =
        res.data.forEach((i) => {
          this.BilltypeOp[i.dictCode] = i.dictName;
        });
      } else {
        this.$exception(res);
      }
    } catch (error) {
      this.$exception(error);
    }
  },

  methods: {
    switchSearch() {
      this.isHideSearch = !this.isHideSearch;
    },

    clickRow(event, rowKey) {
      this.clickStItemLocatorHId = rowKey;
    },

    addItem() {
      this.pkId = null;
      this.visible = true;
    },

    editorItem(item) {
      this.pkId = item.stItemLocatorHId;
      this.visible = true;
    },

    delItem(item) {
      this.$confirm({
        content: this.$lang("是否确定删除?"),
        onOk: () => {
          return this.handleDels({ idList: [item.stItemLocatorHId] });
        },
      });
    },

    reloadTable() {
      this.$refs.table.reload();
    },

    handleDels(p) {
      return delItems(p).then((res) => {
        if (!res.success) {
          this.$exception(res.message);
          return;
        }
        this.$message.success("删除成功");
        this.reloadTable();
      });
    },
    doneBefore(data) {
      console.log(data);
      data.data.list.forEach((i) => {
        // i.billtype = "1,7";
        let a = [];
        let b = [];
        if (i.billtype) {
          a = i.billtype.split(",");
        }
        a.forEach((t) => {
          if (this.BilltypeOp[t]) {
            b.push(this.BilltypeOp[t]);
          }
        });
        i.billtype = b.join();
      });
      console.log(data);

      return data;
    },
    handleQueryItems(list) {
      if (!list || list.lenght == 0) {
        return list;
      }
      let itemIds = [];
      list.forEach((t) => {
        if (t.itemId == "all") return;
        if (!itemIds.some((tt) => tt == t.itemId)) itemIds.push(t.itemId);
      });
      if (itemIds.length == 0) {
        this.list = list;
        return list;
      }
      console.log(list, "===");
      queryItemInfos({ itemIds: itemIds }).then((res) => {
        if (!res.success) {
          this.$exception(res.message);
          return;
        }
        let nlist = list.map((t) => {
          let item = res.data.list.find((tt) => tt.itemId == t.itemId);
          if (item)
            return {
              ...t,
              caseUom: item.caseUom,
              caseConversionRate: item.caseConversionRate,
              itemHealthType: item.itemHealthType,
              pieceConversionRate: item.pieceConversionRate,
              storeTemperature: item.storeTemperature,
            };
          else return t;
        });
        this.list = nlist;
      });
      this.list = list;
      return list;
    },
  },
};
</script>
<style scoped>
.btn {
  color: #2b80ff;
  margin-right: 10px;
  cursor: pointer;
}
.btn:hover {
  text-decoration: underline;
}
</style>
