<script>
import { TableColumns, BasicColumns } from "./column";
import { initDicts } from "@/utils/init.js";
import { FIRSTDIRECT, ADD } from "@/api/business/purchase/task";
export default {
  name: "FirstDirectPurchaseDrawer",
  dicts: [...initDicts(TableColumns)],
  props: {
    selectData: {
      type: [Array],
      require: true,
    },
  },
  components: {
    ElSuperTable: () => import("@/components/super-table/index.vue"),
    ElDictTag: () => import("@/components/DictTag/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElComputedInputV2: () => import("@/components/computed-input-v2/index.vue"),
  },
  data() {
    return {
      title: "订单生成",
      width: "100%",
      column: 1,
      visible: false,
      loading: false,
      tableColumns: TableColumns,
      basicColumns: BasicColumns,
      data: [],
      showData: [],
      supplier: "",
      size: "mini",
    };
  },
  computed: {
    disabled: {
      get() {
        return !this.selectData.length;
      },
      set() {},
    },
    restaurants: {
      get() {
        let allSupplier = [];
        this.data.forEach((item) => {
          let orderPriceVos = item.orderPriceVos.map((order) => ({
            value: order.supplierName,
            id: order.supplier,
          }));
          allSupplier.push(...orderPriceVos);
        });
        allSupplier = this.uniqueFunc(allSupplier, "id");
        console.log(allSupplier, "allSupplier");
        return allSupplier;
      },
      set() {},
    },
  },
  watch: {},
  methods: {
    //
    async open(prop) {
      this.visible = await this.fetchItem(prop);
      this.supplier = "";
    },
    //
    hide() {
      this.visible = false;
    },
    //
    async fetchItem(prop) {
      try {
        // try
        this.loading = true;
        const { code, data } = await FIRSTDIRECT(prop);
        if (code === 200) {
          this.data = data.map((item) => ({
            ...item,
            orderPriceVos: item.orderPriceVos.map((cItem) => ({
              ...item,
              customerName: "",
              customer: "",
              ...cItem,
              purchaseQuantity:
                item.orderPriceVos.length === 1
                  ? item.puQty - item.executeQty
                  : undefined,
            })),
          }));

          console.log(this.data, "this.data");
          this.showData = _.cloneDeep(this.data);
          return true;
        } else {
          return false;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    //
    async submit(prop) {
      const params = prop
        .map((item) => ({
          ...item,
          orderPriceVos: item.orderPriceVos.filter(
            (citem) => citem.purchaseQuantity
          ),
        }))
        .filter((item) => item.orderPriceVos.length);
      console.log(params, "params");
      try {
        this.loading = true;
        // try
        const { msg, code } = await ADD(params);
        if (code === 200) {
          this.hide();
          this.$emit("success");
          this.$notify.success({ title: msg, duration: 3000 });
        }
      } catch (err) {
        // catch
      } finally {
        // finally
        this.loading = false;
      }
    },
    hide() {
      this.visible = false;
    },
    supplierChange(value) {
      console.log(value, "value");
    },
    // 建议值
    querySearch(queryString, cb) {
      let results = this.restaurants;

      results = queryString
        ? results.filter(this.createFilter(queryString))
        : results;

      //cb是回调函数，返回筛选出的结果数据到输入框下面的输入列表
      cb(results);
    },
    createFilter(queryString) {
      return (item) => {
        return item.value.toUpperCase().match(queryString.toUpperCase());
      };
    },

    handleSelect(prop) {
      console.log(this.data, "handleSelect");

      // this.tableColumns = this.tableColumns.map(({ item, attr }) =>{

      //   if(item['key'] === 'supplierName'){
      //     item.filter = [prop.value];
      //   }

      //   return {
      //     item: {...item},
      //     attr: {...attr},
      //   }

      // })

      // this.$refs.superTable.forEach(item =>{

      //   let { onFilter, onFilters } = item;

      //   let supplierFilter = {
      //     item:{
      //       key: 'supplierName',
      //       title: '供应商',
      //       filterabled:true,

      //     },
      //     attr: {}
      //   }

      //   onFilters(supplierFilter);
      //   onFilter();
      // })

      this.showData = this.data.map((item) => {
        return {
          ...item,
          orderPriceVos: item.orderPriceVos.filter(
            (order) => order.supplier === prop.id
          ),
        };
      });
    },
    handleClear() {
      this.showData = _.cloneDeep(this.data);
    },
    // 对象数组去重
    uniqueFunc(arr, uniId) {
      const res = new Map();
      return arr.filter(
        (item) => !res.has(item[uniId]) && res.set(item[uniId], 1)
      );
    },
    changeQuantity(prop, value) {
      this.data = this.data.map((item) => {
        if (item.id === prop.id) {
          item.orderPriceVos = item.orderPriceVos.map((order) => {
            if (order.id === value.id) {
              return value;
            }

            return order;
          });

          // item.orderPriceVos.forEach(order =>{

          //   if(order.id === value.id){

          //     let change = prop.orderPriceVos.filter(order => order.id === value.id);

          //     order = {...change};

          //   }

          // })
        }
        return item;
      });

      // 实时统计
      this.$refs.superTable[0].updateFooter();
    },
    changeDatePlan(prop, value) {
      this.data = this.data.map((item) => {
        if (item.id === prop.id) {
          item.orderPriceVos = item.orderPriceVos.map((order) => {
            if (order.id === value.id) {
              return value;
            }

            return order;
          });
        }
        return item;
      });
    },
    changeNote(prop, value) {
      this.data = this.data.map((item) => {
        if (item.id === prop.id) {
          item.orderPriceVos = item.orderPriceVos.map((order) => {
            if (order.id === value.id) {
              return value;
            }

            return order;
          });
        }
        return item;
      });
    },
  },
  created() {},
  mounted() {},
  updated() {
    // this.$refs.superTable && this.$refs.superTable[0].doLayout();
  },
  destroyed() {},
};
</script>

<template>
  <el-button
    v-bind="$attrs"
    v-on="$listeners"
    :disabled="disabled"
    @click="open(selectData)"
  >
    {{ title }}
    <el-drawer
      :show-close="false"
      :size="width"
      :title="title"
      v-loading="loading"
      :visible.sync="visible"
      append-to-body
    >
      <template slot="title">
        <span>{{ title }}</span>

        <el-button
          type="primary"
          :size="$attrs.size"
          @click="submit(data)"
          v-loading="loading"
          >确 认</el-button
        >
        <el-button :size="$attrs.size" @click="hide" v-loading="loading"
          >取 消</el-button
        >
      </template>

      <el-row style="padding: 0 16px">
        <el-col>
          <el-autocomplete
            class="inline-input"
            :size="size"
            v-model="supplier"
            clearable
            :fetch-suggestions="querySearch"
            placeholder="请输入供应商"
            @select="handleSelect"
            @clear="handleClear"
          ></el-autocomplete>
        </el-col>
      </el-row>

      <div v-for="(item, index) in showData" :key="index" class="m-4">
        <template v-if="item.orderPriceVos.length">
          <el-descriptions :column="4">
            <template slot="title">
              <template>
                <span style="margin-right: 10px">{{ item.materialName }}</span>
                <span style="color: tomato">{{ item.puQty }}</span>
                (<span style="color: tomato">{{
                  item.puQty - (item.executeQty || 0)
                }}</span
                >) <span> {{ item.puUnitName }}</span>
              </template>
            </template>

            <el-descriptions-item
              v-for="(basic, bIndex) in basicColumns"
              :key="bIndex"
              :label="basic.item.title"
              >{{ item[basic.item.key] }}
            </el-descriptions-item>
            <el-descriptions-item label="需求数量"
              >{{ item.puQty - (item.executeQty || 0) }}
            </el-descriptions-item>
          </el-descriptions>

          <el-super-ux-table
            v-if="visible"
            ref="superTable"
            v-model="item.orderPriceVos"
            height="auto"
            :columns="tableColumns"
            :size="$attrs.size"
            :dict="dict"
            showSummary
            firstSummary
          >
            <!-- showSummary -->
            <template slot="purchaseQuantity" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                :max="scope.attr.max(scope.row)"
                @change="changeQuantity(item, scope.row)"
              >
              </component>
            </template>
            <template slot="arrivalDatePlan" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                @change="changeDatePlan"
              >
              </component>
            </template>
            <template slot="note" slot-scope="scope">
              <component
                v-bind="scope.attr"
                v-model="scope.row[scope.item.key]"
                :size="$attrs.size"
                @change="changeNote"
              >
              </component>
            </template>
          </el-super-ux-table>
        </template>
      </div>
    </el-drawer>
  </el-button>
</template>

<style scoped></style>
