<template>
  <basic-page-list ref="listPage" :desc="desc" @importData="pageImport"  :options="pageOptions"></basic-page-list>
</template>

<script>
import BASE_URL from '@/services/mes/api.js';


export default {
  i18n: require("./i18n"),
  props: {

  },
  data() {
    return {
      pageOptions: {}
    };
  },
  // 计算属性
  computed: {
    // 页面描述
    desc() {
      return this.$t("pageDesc");
    }
  },


  // 创建完成
  created() {
    this.optionsInit();
  },
  // 动作
  methods: {


    loadMaterials({ materials_names }) {
      return this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/list`,
        data: {
          "page": 1,
          "limit": 100000,
          "end_time": 0,
          "start_time": 0,
          "order_bys": [
          ],
          "search_rules": [
            { "column": "name", "mode": "in", "value": materials_names.join(",") }
          ]
        },
        useBigInt: true
      });
    },
    loadWarehouses({ warehouse_names }) {
      return this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MesWarehouse/v1/mes/warehouse/list`,
        data: {
          "page": 1,
          "limit": 100000,
          "end_time": 0,
          "start_time": 0,
          "order_bys": [
          ],
          "search_rules": [
            { "column": "warehouse_name", "mode": "in", "value": warehouse_names.join(",") }
          ]
        },
        useBigInt: true
      });
    },
    pageImport({ data }) {
       

      let dataRows = [];
      var materials_names = [];
      var warehouse_names = [];
      var materials_list = [];
      var warehouse_list = [];


      data.forEach(item => {
        let dataRow = {};
        this.pageOptions.exportColumns.forEach(col => {

          if (col.title in item) {
            let v = item[col.title];
            dataRow[col.field] = v;
          }
        })
        dataRows.push(dataRow);
      });


      dataRows.forEach(item => {
        if (item.parent_material_name) {
          let v = item.parent_material_name;
          if (!materials_names.filter(a => a == v).length) {
            materials_names.push(v);
          }
        }

        if (item.child_material_name) {
          let v = item.child_material_name;
          if (!materials_names.filter(a => a == v).length) {
            materials_names.push(v);
          }
        }

        if (item.parent_warehouse_name) {
          let v = item.parent_warehouse_name;
          if (!warehouse_names.filter(a => a == v).length) {
            warehouse_names.push(v);
          }
        }
        if (item.child_warehouse_name) {
          let v = item.child_warehouse_name;
          if (!warehouse_names.filter(a => a == v).length) {
            warehouse_names.push(v);
          }
        }

      });


      
      console.log(dataRows,materials_names,warehouse_names);


      let getMaterialId = ({ name }) => {
        if (!name) return 0;
        for (let i = 0; i < materials_list.length; i++) {
          if (materials_list[i].name == name) {
            return materials_list[i].id;
          }
        }
        return 0;
 
      } 
      let getWarehouseId = ({ name }) => {
        if (!name) return 0;
        for (let i = 0; i < warehouse_list.length; i++) {
          if (warehouse_list[i].warehouse_name == name) {
            return warehouse_list[i].id;
          }
        }
        return 0;

      }

      let getParents = () => {
        let rows = [];
        dataRows.forEach(item => {

          let material_id = getMaterialId({ name: item.parent_material_name });

          if (material_id && rows.filter(a => a.material_id == material_id && a.version == item.parent_version).length == 0) {

            let warehouse_id = getWarehouseId({ name: item.parent_warehouse_name });

            rows.push({
              material_id: material_id, 
              warehouse_id: warehouse_id,
              version: (item.parent_version || "").toString(),
              is_default: item.is_default == "1" ? 1 : 0
            })
          }


        });

        return rows;

      }
      let getChidlren = ({ parent }) => {
        let rows = [];
        dataRows.forEach(item => {

          let material_id = getMaterialId({ name: item.parent_material_name });
          let child_material_id = getMaterialId({ name: item.child_material_name });

          if (material_id &&
            parent.material_id == material_id &&
            parent.version == item.parent_version &&
            child_material_id &&
            rows.filter(a => a.material_id == child_material_id).length == 0) {

            let warehouse_id = getWarehouseId({ name: item.child_warehouse_name });

            rows.push({
              material_id: child_material_id,
              warehouse_id: warehouse_id,
              loss_rate: parseFloat(item.loss_rate),
              sub_qty: parseFloat(item.sub_qty)
            })
          }

        });

        return rows;

      }
      let getImportData = () => {
        let parentData = getParents();
        let data = [];
        parentData.forEach(item => {
          let children = getChidlren({ parent: item });
          if (children.length) {

            data.push({
              parent: item,
              child: children
            })
          }


        })
        return data;

      }

      let startImport = () => {
        let data = getImportData();
        if (!data.length) {
          this.$mk.error("无可导入数据");
          return;
        }
        console.log(data)
        this.$mk.post({
          url: `${BASE_URL.BASE_URL}/MesBom/v1/mes/bom/batchCreateParentAndChild`,
          loading: "导入中...",
          data: {
            "bom": data
          },
          useBigInt: true
        }).then((a) => { // 成功 

          this.$mk.success(a.data.msg || "导入成功"); // 提示成功
          this.$refs.listPage.gridReload(); 
        }).catch((a) => { // 失败
          this.$mk.error(a.data.msg); // 提示错误信息
        });

      }

      if(!materials_names.length){
        this.$mk.error("没有可导入数据"); // 提示错误信息
        return;
      }
      this.loadMaterials({ materials_names }).then((a) => {
        materials_list = a.data.MesMaterials;

        if(warehouse_names.length){
          this.loadWarehouses({ warehouse_names }).then((b) => {
          warehouse_list = b.data.MesWarehouse;


          startImport();
        })
        }else{
          startImport();
        }
        
      })


    },

    optionsInit() {
      // 页面数据
      var pageData = { // 页面数据变量

        keyName: 'id', // 主键字段名 
        listFieldName: 'MesBom',
        addPageUrl: "/MesBom/MesBomAdd",
        editPageUrl: "/MesBom/MesBomUpdate/",
        // 接口动作
        actions: { // Api 接口地址 
          MesBomList: `${BASE_URL.BASE_URL}/MesBom/v1/mes/bom/list`,
          MesBomBatchDelete: `${BASE_URL.BASE_URL}/MesBom/v1/mes/bom/batchDelete`
        },

        start_time: 0, // 开始时间
        end_time: 0, // 结束时间

        exportFileTitle: "物料清单",
        enabledExport: false,
        enabledImport: true,
        enabledImportTemplate: true,
        exportColumns: [
          { title: '父件', field: "parent_material_name" },
          { title: '版本号', field: "parent_version" },
          { title: '默认仓库', field: "parent_warehouse_name" },
          { title: '是否默认', field: "parent_is_default" },
          { title: '子件', field: "child_material_name" },
          { title: '预出仓库', field: "child_warehouse_name" },
          { title: '需用数量', field: "sub_qty" },
          { title: '损耗率', field: "loss_rate" },
        ],


        //搜索区
        searchFormData: {
          title: '',
          desc: '',
        },
        // 搜索区配置
        searchRules: [
          { key: "title", mode: "equal" },
          { key: "version", mode: "like" }
        ],
        //搜索区
        searchFormItems: [ // 子项

          {
            title: '父件', span: 6,
            field: 'material_id',
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "object",
                  valueField: "id",
                  textField: "name",
                  listdataFieldName: 'MesMaterials',
                  dataUrl: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/list`
                }
              }
            }
          },
          { field: 'version', title: '版本号', span: 6, itemRender: { name: '$input', props: { placeholder: '请输入版本号' } } },

          {
            align: 'right', span: 4, itemRender: {  // 按钮列
              name: '$buttons', children: [{ props: { type: 'submit', content: '搜索', status: 'primary' } },  // 搜索按钮
              { props: { type: 'reset', content: '重置' } }]
            }
          }
        ],


        //数据区
        gridOptions: { // 表格配置
          height: '100%', // 表格高度  100% 会自动撑满父容器
          stripe: true, // 启用斑马纹
          id: 'datagrid_1', // 表格唯一标识

          // 表格列配置
          columns: [
            { type: 'checkbox', width: 'auto' }, // 多选框
            { type: 'seq', width: 'auto' }, // 序号

            { title: '操作', slots: { default: 'op' }, width: 120 },

            { field: 'mes_materials', formatter: 'formatRef', params: { dataType: "object", textField: "name" }, title: '父件', width: 250 },

            { field: 'version', sortable: true, title: 'BOM版本', width: 250 },

            { field: 'create_time', formatter: 'formatDate', width: 100, sortable: true, title: '创建时间', showHeaderOverflow: true }, // 创建时间
            { field: 'update_time', formatter: 'formatDate', width: 100, sortable: true, title: '更新时间', showHeaderOverflow: true }, // 更新时间

            // =============================== 表格列 自动生成 Start ===============================


          ]
        }

      };

      pageData.actions.getList = pageData.actions.MesBomList;
      pageData.actions.delete = pageData.actions.MesBomBatchDelete;
      pageData.gridOptions = Object.assign({}, this.$mk.config.defaults.gridOptions, pageData.gridOptions); // 合并表格数据


      this.pageOptions = pageData;
    },


  },
  watch: {

  }
};

</script> 