<template>
  <div class="page-body">
    <div class="split_wrapper">
      <div class="left">
        <div class="treepanel">
          <div class="treepanel-header">
            <a @click.stop="treeAdd(row)" title="新增">
              <a-icon type="plus-circle" />
            </a>
            <a @click.stop="treeEdit(row)" title="编辑">
              <a-icon type="edit" />
            </a>
            <a @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" :desc="desc" @importData="pageImport" :options="pageOptions"> 
            <template v-slot:column2="{ row }">  
              <vue-qr class="qr-code"   :text="row.qr_code" :size="120" />
            </template> 
        </basic-page-list>

      </div>
    </div>
  </div>
</template>

<script>
import BASE_URL from '@/services/mes/api.js';
let childrenFieldName = 'children';
import { toArrayTree } from "xe-utils"
const settings = require('../../basic/settings.js');

import vueQr from 'vue-qr';
export default {
  i18n: require("./i18n"),
  props: {

  },
  
  components: { 
    vueQr
  },
  data() {
    return {
      pageOptions: {},

      modelName: "",

      actions: {
        treedata: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/sort/list`,
        delete: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/sort/batchDelete`,
        listdata: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/list`,
        save: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/batchHandle`,
      },
      tipTimes: 0,
      detailsData: [
      ],
      sourceDetailsData: [

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

      ],
      selectedKeys: [],
      selectedKey: null,
      tableHeight: 500
    };
  },
  // 计算属性
  computed: {
    // 页面描述
    desc() {
      return this.$t("pageDesc");
    }
  },


  // 创建完成
  created() {
    this.optionsInit();

    this.$nextTick(() => {

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

    });

  },
  // 动作
  methods: {


    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 = [];
      data.forEach(item => {
        let row = {};
        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);
            } 
            console.log(col.options)
            row[col.field] = v;
          }
        })
        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.xGrid.commitProxy('query') // 提交搜索

      }).catch((a) => { // 失败
        this.$mk.error(a.data.msg); // 提示错误信息
      });
    },
    optionsInit() {
      // 页面数据
      var pageData = { // 页面数据变量

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

        exportFileTitle: "工序",
        enabledExport: true,
        enabledImport: true,
        enabledImportTemplate: true,
        exportColumns: [
          { title: '编码', field: "code" },
          { title: '工序名称', field: "name" },
          { title: '工序描述', field: "desc" },
          { title: '计工方式', field: "work_type", options: settings.options_work_type },
          { title: '工序分类', field: "sort_id", dataField: 'mes_processes_sort', textField: "name" }
        ],
        addPageUrl: "/MesProcesses/MesProcessesAdd",
        editPageUrl: "/MesProcesses/MesProcessesUpdate/",

        // 接口动作
        actions: { // Api 接口地址
          // =============================== 接口地址 自动生成 Start ===============================
          MesProcessesList: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/list`, // 工序列表
          MesProcessesDetail: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/detail`, // 工序详情
          MesProcessesCreate: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/create`, // 创建工序
          MesProcessesUpdate: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/update`, // 更新工序
          MesProcessesDelete: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/detele`, // 删除工序
          MesProcessesBatchDelete: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/batchDelete`, // 批量删除工序
          MesProcessesBatchUpdate: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/batchUpdate`, // 批量更新工序
          MesProcessesBatchCreate: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/batchCreate`, // 批量创建工序
          MesProcessesExportExcel: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/export/excel`, // 导出工序数据到EXCEL
          MesProcessesImportExcel: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/import/excel`, // 批量导入EXCEL工序数据
          MesProcessesOpen: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/open`, // 打开工序
          MesProcessesClose: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/close`, // 关闭工序
          ProcessProgrammeList: `${BASE_URL.BASE_URL}/MesProcesses/v1/process/programme/list`, // 工序方案列表
          ProcessProgrammeDetail: `${BASE_URL.BASE_URL}/MesProcesses/v1/process/programme/detail`, // 工序方案详情
          ProcessProgrammeCreate: `${BASE_URL.BASE_URL}/MesProcesses/v1/process/programme/create`, // 创建工序方案
          ProcessProgrammeUpdate: `${BASE_URL.BASE_URL}/MesProcesses/v1/process/programme/update`, // 更新工序方案
          ProcessProgrammeDelete: `${BASE_URL.BASE_URL}/MesProcesses/v1/process/programme/detele`, // 删除工序方案
          ProcessProgrammeBatchDelete: `${BASE_URL.BASE_URL}/MesProcesses/v1/process/programme/batchDelete`, // 批量删除工序方案
          ProcessProgrammeBatchUpdate: `${BASE_URL.BASE_URL}/MesProcesses/v1/process/programme/batchUpdate`, // 批量更新工序方案
          ProcessProgrammeBatchCreate: `${BASE_URL.BASE_URL}/MesProcesses/v1/process/programme/batchCreate`, // 批量创建工序方案
          ProcessProgrammeExportExcel: `${BASE_URL.BASE_URL}/MesProcesses/v1/process/programme/export/excel`, // 导出工序方案数据到EXCEL
          ProcessProgrammeImportExcel: `${BASE_URL.BASE_URL}/MesProcesses/v1/process/programme/import/excel`, // 批量导入EXCEL工序方案数据
          ProgrammeItemList: `${BASE_URL.BASE_URL}/MesProcesses/v1/programme/item/list`, // 工序方案工序ID列表
          ProgrammeItemDetail: `${BASE_URL.BASE_URL}/MesProcesses/v1/programme/item/detail`, // 工序方案工序ID详情
          ProgrammeItemCreate: `${BASE_URL.BASE_URL}/MesProcesses/v1/programme/item/create`, // 创建工序方案工序ID
          ProgrammeItemUpdate: `${BASE_URL.BASE_URL}/MesProcesses/v1/programme/item/update`, // 更新工序方案工序ID
          ProgrammeItemDelete: `${BASE_URL.BASE_URL}/MesProcesses/v1/programme/item/detele`, // 删除工序方案工序ID
          ProgrammeItemBatchDelete: `${BASE_URL.BASE_URL}/MesProcesses/v1/programme/item/batchDelete`, // 批量删除工序方案工序ID
          ProgrammeItemBatchUpdate: `${BASE_URL.BASE_URL}/MesProcesses/v1/programme/item/batchUpdate`, // 批量更新工序方案工序ID
          ProgrammeItemBatchCreate: `${BASE_URL.BASE_URL}/MesProcesses/v1/programme/item/batchCreate`, // 批量创建工序方案工序ID
          ProgrammeItemExportExcel: `${BASE_URL.BASE_URL}/MesProcesses/v1/programme/item/export/excel`, // 导出工序方案工序ID数据到EXCEL
          ProgrammeItemImportExcel: `${BASE_URL.BASE_URL}/MesProcesses/v1/programme/item/import/excel`, // 批量导入EXCEL工序方案工序ID数据

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

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


        //搜索区
        searchFormData: {
          title: '',
          desc: '',
        },
        // 搜索区配置
        searchRules: [
          { key: "name", mode: "like" },
          { key: "code", mode: "like" },
          { key: "sort_id", mode: "in" },
        ],
        //搜索区
        searchFormItems: [ // 子项
          { field: 'name', title: '工序名称', span: 4, itemRender: { name: '$input', props: { placeholder: '请输入工序名称' } } },
          { field: 'code', title: '编码', span: 4, itemRender: { name: '$input', props: { placeholder: '请输入编码' } } },
          { span: 6, slots: { default: 'date' } },  // 自定义列
          {
            align: 'left', 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 },

            { slots: { default: 'column2' }, title: '扫码', width: 130 },
            // =============================== 表格列 自动生成 Start ===============================

            //{ field: 'process_segment_id', sortable: true, title: '工序段id', width: 250 }, // 工序段id
            //{ field: 'title', sortable: true, title: '工序名称', width: 250 }, // 工序名称
            { field: 'code', sortable: true, title: '工序编码', width: 250 }, // 工序编码
            { field: 'name', sortable: true, title: '工序名称', width: 250 },

            { field: 'mes_processes_sort', formatter: 'formatRef', params: { dataType: "object", textField: "name" }, title: '工序分类', width: 250 },

            { field: 'desc', sortable: true, title: '工序描述', width: 250 }, // 工序描述
            { field: 'remark', sortable: true, title: '工序备注', width: 250 }, // 工序备注 

            { field: 'work_type', params: settings.options_work_type, formatter: 'formatEnum', sortable: true, title: '计工方式', width: 250 },

            { field: 'car_limit', sortable: true, title: '领车限制数', width: 250 }, // 领车限制数
            { field: 'is_quality_inspection', sortable: true, title: '是否质检工序', width: 250 }, // 是否质检工序
            //{ field: 'quality_inspection_scheme_id', sortable: true, title: '质检方案id', width: 250 }, // 质检方案id
            //{ field: 'raw_material_type_id', sortable: true, title: '坯体类型ID', width: 250 }, // 坯体类型ID
            { field: 'status', slots: { default: 'status' }, width: 80, sortable: true, title: '状态', showHeaderOverflow: true }, // 状态

            { 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.MesProcessesList;
      pageData.actions.delete = pageData.actions.MesProcessesBatchDelete;
      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.MesProcessesSort;
        let at = toArrayTree(r.data.MesProcessesSort, { 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;
        }
      }
    },
    ok() {

      let save = () => {

        if (!this.selectedKey || this.selectedKey == "root") {
          this.$mk.error("请先选择料品分类");
          return;
        }
        let node = this.findTreeNode(this.selectedKey);

        let ds = JSON.parse(JSON.stringify(this.detailsData));

        var postdata = {
          insertList: [],
          updateList: [],
          deleteList: this.deletedDetailsData
        };

        ds.forEach(item => {
          delete item._X_ROW_KEY;

          item.enum_id = node.id;
          if (item.id && item.id != "0") {
            let source = this.findSourceInfo(item.id);
            item.id = source.id;
            postdata.updateList.push(item);
          } else {
            postdata.insertList.push(item);
          }
        })
        this.$mk.post({
          url: this.actions.save,
          loading: "保存中...",
          data: postdata,
          useBigInt: true
        }).then(a => {
          if (a.code == "200") {
            this.$mk.success("保存成功");
            this.reloadData();
          } else {
            this.$mk.error(a.message);
          }


        }).catch((a) => {
          this.$mk.error(a.data.msg);
        });
      };

      save();


    },

    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>
