<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"),
    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);
    },
    //
    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
            })),
          }));

          this.showData = _.cloneDeep(this.data);

          console.log(this.data,'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);
      try {
        // 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
      }
    },
    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(prop,'prop');
      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));
    },
  },
  created() {},
  mounted() {},
  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"
      :visible.sync="visible"
      append-to-body
    >
      <template slot="title">
        <span>{{ title }}</span>

        <el-button
          type="primary"
          :size="$attrs.size"
          :loading="loading"
          @click="submit(data)"
          >确 认</el-button
        >
        <el-button
          :size="$attrs.size"
          :loading="loading"
          @click="hide"
          >取 消</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>
            <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-table
            v-model="item.orderPriceVos"
            :columns="tableColumns"
            :size="$attrs.size"
            :dict="dict"
          >
            <!-- 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)"
              >
              </component>
            </template>
          </el-super-table>
        </template>
        
      </div>
    </el-drawer>
  </el-button>
</template>

<style scoped></style>
