<template>
  <div class="page-body">


    <div class="split_wrapper">
      <div class="left">
        <div class="treepanel" :style="'height:' + tableHeight + 'px'">
          <div class="treepanel-header">
            <a style="margin-left: 10px;" class="link" @click.stop="treeAdd(row)" title="新增">
              <a-icon type="plus-circle" />
            </a>
            <a class="link" @click.stop="treeEdit(row)" title="编辑">
              <a-icon type="edit" />
            </a>
            <a class="link" @click.stop="treeDelete(row)" title="删除">
              <a-icon type="delete" />
            </a>
          </div>
          <div class="treepanel-content">
            <a-tree v-if="!treeLoading" show-line :tree-data="treeData" :default-expand-all="true" :block-node="true"
              @select="onTreeSelect" :default-selected-keys="selectedKeys">
              <a-icon slot="switcherIcon" type="down" />
            </a-tree>
          </div>
        </div>

      </div>
      <div class="right">

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

      </div>
    </div>













  </div>
</template>

<script>


import BASE_URL from '@/services/mes/api.js';
let childrenFieldName = 'children';
import { toArrayTree } from "xe-utils"
export default {

  props: {
    pageMode: {
      type: String,
      default: "edit"
    },
    dataId: {
    }

  },

  data() {

    // 页面数据变量
    var pageData = {

      pageOptions: {},

      modelName: "",
      attributes: [],
      typeData: [],
      actions: {
        treedata: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/sort/list`,
        delete: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/sort/batchDelete`,

        productAttribute: `${BASE_URL.BASE_URL}/MesProductCustomAttribute/v1/get/productAttribute`
      },
      tipTimes: 0,
      detailsData: [
      ],
      sourceDetailsData: [

      ],
      treeData: [],
      treeLoading: true,
      deletedDetailsData: [

      ],
      selectedKeys: [],
      selectedKey: null,
      tableHeight: 500

    };


    return pageData;
  },
  created() {

    this.attributeDataInit();
    this.optionsInit();
    this.$nextTick(() => {

      this.tableHeight = this.$mk.getWindowSize().height - 320;
      this.treeInit();

    });



  },
  // 函数
  methods: {


    attributeDataInit() {
      this.$mk.post({
        url: this.actions.productAttribute,
        loading: "加载中..."
      }).then(a => {

        this.attributes = a.data.attribute;
        this.attributes.forEach(item => {

          this.pageOptions.exportColumns.push(
            {
              title: item.name, type: "attribute", valueGetter: this.getExportAttributeValue
            });

        })




      }).catch((a) => {
        this.$mk.error(a.data.msg);
      });
    },
    getAttribute(name) {
      for (let i = 0; this.attributes && i < this.attributes.length; i++) {
        if (this.attributes[i].name == name) {
          return this.attributes[i];
        }
      }
      return null;
    },
    getAttributeId(name) {
      for (let i = 0; this.attributes && i < this.attributes.length; i++) {
        if (this.attributes[i].name == name) {
          return this.attributes[i].id;
        }
      }
      return null;
    },
    getAttributeValue({ row, attribute_id }) {
      for (let i = 0; row.custom_attribute_value && i < row.custom_attribute_value.length; i++) {
        if (row.custom_attribute_value[i].attribute_id.toString() == attribute_id.toString()) {
          return row.custom_attribute_value[i].value;
        }
      }
      return '';
    },
    getExportAttributeValue({ row, column }) {
      console.log(row, column, this.attributes)
      let attrid = this.getAttributeId(column.title);
      if (!attrid) return '';
      return this.getAttributeValue({ row: row, attribute_id: attrid })

    },
    getTypeId(name) {
      for (let i = 0; i < this.typeData.length; i++) {
        if (this.typeData[i].name == name) {
          return this.typeData[i].id;
        }
      }
      return 0;
    },
    getOptionValue({ label, options }) {
      for (let i = 0; i < options.length; i++) {
        if (options[i].label == label) {
          return options[i].value;
        }
      }
      return '';
    },

    pageImport({ data }) {
      let rows = [];
      console.log(data)
      data.forEach(item => {
        let row = {
          custom_attribute_value: []

        };
        this.pageOptions.exportColumns.forEach(col => {

          if (col.title in item) {
            let v = item[col.title];
            if (col.options) {
              v = this.getOptionValue({ options: col.options, label: v });
            } else if (col.field == "sort_id") {
              v = this.getTypeId(v);
            }
            else if (col.type == "attribute") {
              let attrid = this.getAttributeId(col.title);
              if (!attrid) return;
              let attr = this.getAttribute(col.title);
              v = v || ""
              if (attr.typeName == '7') {
                v = (v == "1" || v == "TRUE" || v == "true" || v == "True") ? "true" : "false";
              }
              if (attr.typeName == "3" || attr.typeName == "4" || attr.typeName == "5") {
                // 将数字转换为日期格式
                let date = new Date((v - 1) * 24 * 60 * 60 * 1000 + 1);

                v = date.getFullYear() + '-' + (date.getMonth() + 1).toString().padStart(2, '0') + '-' + date.getDate().toString().padStart(2, '0');

              }
              row.custom_attribute_value.push({
                attribute_id: attrid,
                "value": v.toString(),
                "e_value": v.toString()
              })
              return;
            }
            row[col.field] = v;
          }
        })

        if(row.code && row.name){
          rows.push(row);
        }
       
      });

      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/batchCreate`,
        loading: "导入中...",
        data: {
          "list": rows
        },
        useBigInt: true
      }).then((a) => { // 成功 

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

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

        keyName: 'id', // 主键字段名 
        listFieldName: 'MesMaterials',

        addPageUrl: "/MesMaterials/MesMaterialsAdd",
        editPageUrl: "/MesMaterials/MesMaterialsUpdate/",


        enabledExport: true,
        enabledImport: true,
        enabledImportTemplate: true,
        exportColumns: [
          { title: '编码', field: "code" },
          { title: '料品', field: "name" },
          { title: '规格型号', field: "spec" },
          { title: '分类', field: "sort_id", dataField: 'mes_materials_sort', textField: "name" },



        ],

        // 接口动作
        actions: { // Api 接口地址
          // =============================== 接口地址 自动生成 Start ===============================
          MesMaterialsList: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/list`, // 料品列表
          MesMaterialsDetail: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/detail`, // 料品详情
          MesMaterialsCreate: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/create`, // 创建料品
          MesMaterialsUpdate: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/update`, // 更新料品
          MesMaterialsDelete: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/detele`, // 删除料品
          MesMaterialsBatchDelete: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/batchDelete`, // 批量删除料品
          MesMaterialsBatchUpdate: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/batchUpdate`, // 批量更新料品
          MesMaterialsBatchCreate: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/batchCreate`, // 批量创建料品
          MesMaterialsExportExcel: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/export/excel`, // 导出料品数据到EXCEL
          MesMaterialsImportExcel: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/import/excel`, // 批量导入EXCEL料品数据

          // =============================== 接口地址 自动生成 End ===============================
        },

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


        //搜索区
        searchFormData: {
          title: '',
          desc: '',
        },
        // 搜索区配置
        searchRules: [
          { key: "name", mode: "like" },
          { key: "sort_id", mode: "in" },

        ],
        //搜索区
        searchFormItems: [ // 子项
          { field: 'name', title: '料品名', span: 5, itemRender: { name: '$input', props: { placeholder: '请输入料品名' } } },
          { span: 8, slots: { default: 'date' } },  // 自定义列
          {
            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 },

            // =============================== 表格列 自动生成 Start ===============================
            { field: 'code', sortable: true, title: '编码', width: 250 }, // 编码
            { field: 'name', sortable: true, title: '名称', width: 250 },



            { field: 'spec', title: '规格型号', width: 150 },
            { field: 'size', title: '尺寸', width: 150 },
            { field: 'color', title: '颜色', width: 150 },
            { field: 'face', title: '花面', width: 150 },
            { field: 'molding', title: '成型方式', width: 150 },
            { field: 'production_type', title: '布产方式', width: 150 },

            { field: 'theoretical_load', title: '理论装车量', width: 150 },
            { field: 'soil', title: '土质', width: 150 },
            { field: 'unit', title: '单位', width: 150 },
            { 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.MesMaterialsList;
      pageData.actions.delete = pageData.actions.MesMaterialsBatchDelete;
      pageData.gridOptions = Object.assign({}, this.$mk.config.defaults.gridOptions, pageData.gridOptions); // 合并表格数据


      this.pageOptions = pageData;
    },
    treeInit() {
      this.treeLoading = true;
      this.$mk.post({
        url: this.actions.treedata,
        loading: "加载中...",
        data: {
          "page": 1,
          "limit": 10000,
          "end_time": 0,
          "start_time": 0,
          "order_bys": [
          ],
          "search_rules": [
          ]
        }
      }).then(r => {


        let treedata = {
          title: "料品分类",
          key: "root"
        };
        this.typeData = r.data.MesMaterialsSort;
        let at = toArrayTree(r.data.MesMaterialsSort, { parentKey: "parent_id" });
        console.log(at);
        treedata[childrenFieldName] = at;


        function formatTreedata(d) {
          if (d.id) {
            d.key = d.id.toString();
          } else {
            d.key = "root";
          }
          if (d.name) {
            d.title = d.name;
          }
          if (d[childrenFieldName] && d[childrenFieldName].length) {
            d[childrenFieldName].forEach(item => formatTreedata(item))
          }
        }
        treedata[childrenFieldName].forEach(item => formatTreedata(item))

        this.treeData = [treedata];
        this.treeLoading = false;
      });

    },
    treeAdd() {
      this.$mk.dialog.open({
        page: () => import("./treeEdit"),
        title: "新增-料品分类",
        dataId: 0,
        callback: ({ success }) => {
          success && this.treeInit();
        }
      })
    },
    treeEdit() {
      if (!this.selectedKey || this.selectedKey == "root") {
        this.$mk.error("请先选择料品分类");
        return;
      }
      let node = this.findTreeNode(this.selectedKey);


      this.$mk.dialog.open({
        page: () => import("./treeEdit"),
        title: "编辑-料品分类",
        dataId: node.id,
        callback: ({ success }) => {
          success && this.treeInit();
        }
      })
    },
    treeDelete() {
      if (!this.selectedKey || this.selectedKey == "root") {
        this.$mk.error("请先选择料品分类");
        return;
      }
      let node = this.findTreeNode(this.selectedKey);
      let ids = [
        node.id
      ]; // 定义id数组

      if (!ids.length) {  // 如果没有选中行
        this.$mk.error("请选择行"); // 提示
        return;
      }

      this.$mk.confirm('您确定要删除吗？').then(type => { // 确认删除
        if (type == 'confirm') { // 如果确认删除
          this.$mk.post({
            url: this.actions.delete, // 请求删除数据地址
            loading: "删除中...", // 加载提示
            data: {
              ids: ids // 传递id数组
            },
            useBigInt: true
          }).then(() => { // 成功
            this.$mk.success("删除成功"); // 提示成功
            this.treeInit(); // 重新加载数据
          }).catch((a) => { // 失败
            this.$mk.error(a.data.msg); // 提示错误信息
          });
        }
      });
    },
    getDataId() {

      let dataId = this.dataId;
      if (this.$route.params.id) {
        dataId = this.$route.params.id;
      }

      return dataId;
    },


    onTreeSelect(selectedKeys) {
      if (selectedKeys && selectedKeys[0]) {
        this.selectedKey = selectedKeys[0];
        this.loadData(selectedKeys[0]);
      }
    },
    findTreeNode(key) {
      var find = (items) => {
        for (let i = 0; i < items.length; i++) {
          if (items[i].key == key) {
            return items[i];
          }
          if (items[i][childrenFieldName] && items[i][childrenFieldName].length) {
            var xx = find(items[i][childrenFieldName]);
            if (xx) {
              return xx;
            }
          }
        }
      };
      return find(this.treeData);
    },
    reloadData() {
      if (this.selectedKey) {
        this.loadData(this.selectedKey);
      }

    },

    getAllChildrenIds(items) {
      let ids = [];
      let eachItems = (arr) => {
        arr.forEach(item => {
          if (item.children && item.children.length) {
            eachItems(item.children);
          } else {
            ids.push(item.id);
          }

        })
      };
      eachItems(items);
      return ids;
    },
    loadData(key) {

      if (key && key != "root") {
        var node = this.findTreeNode(key);
        if (node.children && node.children.length) {
          var ids = this.getAllChildrenIds(node.children);
          this.$refs.listPage.onSearch({
            sort_id: [node.id, ...ids].join(',')
          })
        } else {
          this.$refs.listPage.onSearch({
            sort_id: node.id
          })
        }


      } else {
        this.$refs.listPage.onSearch(null);
      }




    },

    findSourceInfo(idStr) {
      for (var i = 0; i < this.sourceDetailsData.length; i++) {
        let o = this.sourceDetailsData[i];
        if (o.id.toString() == idStr) {
          return o;
        }
      }
    },


    back() {
    },

    cancel() {
      this.back();
    },
    pageAdd(row) {

      const $table = this.$refs.xTable
      const record = {
      }
      if (row) {

        this.detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.detailsData.push(record)
      }



    },

    pageDelete(row) {
      const $table = this.$refs.xTable;
      if (row.id) {
        this.deletedDetailsData.push(row.id)
      }
      this.detailsData.splice($table.getRowSeq(row) - 1, 1);

    },

  },
  // 监听属性
  watch: {

  }
};

</script>
<style>
.page-body {
  background: white;
  padding: 8px;
}


.toolbarbtns .ant-btn {
  margin-right: 10px;
}

.toolbarbtns {
  margin-bottom: 5px;
}
</style>
