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

    <vxe-form :data="formOptions.data" ref="xForm" :title-width="formOptions.titleWidth"
      :title-align="formOptions.titleAlign" :rules="formOptions.rules" :items="formOptions.items" titleColon>
    </vxe-form>


    <vxe-table border show-overflow keep-source ref="xTable"   :data="detailsData"
      @pulldownSelected="onPulldownSelected" @popupSelected="onPopupSelected" :export-config="{}"
      @edit-closed="afterEditEvent" @edit-actived="beforeEditEvent"
      :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: beforeEditMethod }">
      <vxe-column width="60">
        <template #default="{ row }">
          <div class="oplinks2">
            <a @click.stop="pageAdd(row)" title="新增">
              <a-icon class="icon" type="plus-circle" />
            </a>
            <a @click.stop="pageDelete(row)" title="删除">
              <a-icon class="icon" type="delete" />
            </a>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="mold_component" title="部件" width="160" :params="editor_component" formatter="formatRef"
        :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
      <vxe-column field="production_type" title="布产类型" width="160" :params="{ data: options_production_type }"
        formatter='formatEnum'
        :edit-render="{ name: '$select', props: { options: options_production_type } }"></vxe-column>

      <vxe-column field="process_uid_info" title="加工人员" width="160" :params="editor_staff" formatter="formatRef"
        :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

    </vxe-table>

    <a-button @click="pageLoadData()" style="margin: 5px;">加载部门工序</a-button>

    <vxe-table border show-overflow keep-source ref="xTable2"  :data="detailsData2"
      @pulldownSelected="onPulldownSelected" @popupSelected="onPopupSelected" :export-config="{}"
      @edit-closed="afterEditEvent" @edit-actived="beforeEditEvent"
      :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: beforeEditMethod }">
      <vxe-column width="60">
        <template #default="{ row }">
          <div class="oplinks2">
            <a @click.stop="pageAdd2(row)" title="新增">
              <a-icon class="icon" type="plus-circle" />
            </a>
            <a @click.stop="pageDelete2(row)" title="删除">
              <a-icon class="icon" type="delete" />
            </a>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="mold_component" title="部件" width="160" :params="editor_component" formatter="formatRef"
        :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
      <vxe-column field="mes_processes" title="工序" width="160" :params="editor_processes" formatter="formatRef"
        :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
    </vxe-table>



    <div class="mk-toolbar" v-if="isEdit">

    </div>

    <div class="footerbar">
      <a-button type="primary" @click="ok">确定</a-button>
      <a-button @click="cancel">取消</a-button>
    </div>

  </div>
</template>

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

export default {

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

  },

  data() {

    //let _this = this;
    // 页面数据变量
    var pageData = {

      options_production_type: [{ value: '1', label: '正常布产' }, { value: '2', label: '委托布产' }],
      // 当前项目名称
      currentConfigName: "",
      // 当前项目ID
      currentBeid: 0,

      uploadDefaultImg: null,
      detailDataFieldName: "mold_scheme",

      actions: {
        get: `${BASE_URL.BASE_URL}/MoldScheme/v1/mold/scheme/detail`,
        create: `${BASE_URL.BASE_URL}/MoldScheme/v1/mold/scheme/create`,
        update: `${BASE_URL.BASE_URL}/MoldScheme/v1/mold/scheme/update`
      },

      keyName: 'id',
      // 是否编辑模式
      isEdit: false,
      // 表单数据
      formOptions: {
        data: {
          material_id: 0,
          warehouse_id: 0,
          version: '',
          is_default: 0
        },
        // 标题宽度
        titleWidth: 100,
        // 标题对齐方式
        titleAlign: 'right',

        // 表单校验规则
        rules: {

          code: [
            { required: true, message: '请输入模型编码' }
          ],
          name: [
            { required: true, message: '请输入模型名称' }
          ],
        },
        // 表单项
        items: [


          {
            title: '左侧',
            span: 18,
            children: [
              { field: 'code', title: '模型编码', span: 24, itemRender: { name: '$input' } },
              { field: 'name', title: '模型名称', span: 24, itemRender: { name: '$input' } },
              /*
                       {
                         title: '分类', span: 12,
                         field: 'mold_scheme_category',
                         dataRule: {
                           fromField: "id",
                           saveField: "mold_category_id" // 如果表单项存储的是对象，将从fromField中取得值保存到saveField
                         },
                         itemRender: {
                           name: 'MkFormDataSelector', props: {
                             params: {
                               dataType: "object",
                               valueField: "id",
                               textField: "name",
                               listdataFieldName: 'MoldSchemeCategory',
                               dataUrl: `${BASE_URL.BASE_URL}/MoldScheme/v1/mold/scheme/category/list`
                             }
                           }
                         }
                       },
                       */

            ]
          },
          {
            title: '右侧',
            span: 5,
            children: [
              { field: 'image', span: 12, itemRender: { name: 'MkFormUploader' } },
            ]
          },


        ]
      },
      // 新增模式表单项
      addModeItems: [

      ],


      table1Height: 200,
      detailsSourceData: [
      ],
      detailsData: [
      ],
      deletedDetailsData: [

      ],

      detailsData2: [
      ],
      deletedDetailsData2: [

      ],
      editor_component: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MoldComponent',
        mapper: [
          { fromField: "id", field: "component_id" }
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MoldComponent/v1/mold/component/list`
      },


      editor_processes: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesProcesses',
        mapper: [
          { fromField: "id", field: "mes_processes_id" }
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/list`
      },


      editor_staff: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesStaff',
        mapper: [
          { fromField: "id", field: "process_uid" }
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MesStaff/v1/mes/staff/list`
      },


    };


    // 合并表单数据及配置
    pageData.formOptions = Object.assign({}, this.$mk.config.defaults.formOptions, pageData.formOptions);

    return pageData;
  },

  computed: {
    desc() {
      return this.$t('editPageDesc')
    }
  },


  created() {


    // 获取路由的id参数
    let dataId = this.getDataId();

    // 如果有id参数，说明是编辑模式
    if (dataId) {
      this.$mk.post({
        url: this.actions.get,
        loading: "加载中...",
        data: { id: this.$mk.toBigInt(dataId) },
        useBigInt: true
      }).then(a => {


        this.formOptions.data = this.$mk.formatDetailData({ data: a.data[this.detailDataFieldName] });

        this.detailsData = JSON.parse(JSON.stringify(a.data[this.detailDataFieldName].mold_scheme_components || []));
        this.detailsData2 = JSON.parse(JSON.stringify(a.data[this.detailDataFieldName].mold_scheme_processes || []));

 

        this.detailsDataInit();

      });

      this.isEdit = true;



    } else {
      // 如果没有id参数，说明是新增模式
      this.addModeItems.forEach(item => {
        this.formOptions.items.push(item);
      })

      this.detailsDataInit();
    }



    this.heightInit();

  },
  // 函数
  methods: {




    heightInit() {

      this.$nextTick(() => {
        let h = this.$mk.getWindowSize().height - this.$mk.getOffsetTop(this.$refs.xTable.$el) - 300;

        this.table1Height = h * 0.5;
      });

    },
    detailsDataInit() {
      for (let i = this.detailsData && this.detailsData.length; i < 1; i++) {
        this.detailsData.push({});
      }
      for (let i = this.detailsData2 && this.detailsData2.length; i < 1; i++) {
        this.detailsData2.push({});
      }
    },
    // 获取路由的id参数
    getDataId() {
      let dataId = this.dataId;
      if (this.$route.params.id) {
        dataId = this.$route.params.id;
      }
      if (!dataId) {
        dataId = 0;
      }
      return dataId;
    },
    getDataId_BigInt() {
      let dataId = this.getDataId();
      return this.$mk.toBigInt(dataId);
    },


    // 返回
    back() {
      // 如果是新增模式，关闭当前页面
      if (!this.isEdit) {
        this.$closePage({
          closeRoute: "/Mold/MoldSchemeAdd"
        });
      } else {
        // 如果是编辑模式，关闭当前页面
        this.$closePage({
          closeRoute: "/Mold/MoldSchemeUpdate"
        });
      }
      // 打开列表页面
      this.$openPage('/Mold/MoldScheme')
    },

    pageLoadData() {
      this.detailsData2.forEach(item => {
        if (item.id) {
          this.deletedDetailsData2.push(this.$mk.toBigInt(item.id))
        }
      })

      console.log(JSON.stringify(this.detailsData2))
      this.detailsData2 = [];
      console.log(this.detailsData);
      let component_ids = [];
      this.detailsData.forEach(item => {
        if (item.component_id) {
          component_ids.push(item.component_id);
        }
      });



      let loadNextComponent = (index) => {

        this.$mk.post({
          url: `${BASE_URL.BASE_URL}/MoldComponent/v1/mold/component/detail`,
          data: {
            id: this.$mk.toBigInt(component_ids[index])
          },
          useBigInt: true
        }).then((a) => { // 成功回调
          if (a.data && a.data.mold_component) {
            let mold_component_processes = a.data.mold_component.mold_component_processes || [];
            let currentAddRows = [];
            mold_component_processes.forEach(pitem => {
              currentAddRows.push({
                component_id: a.data.mold_component.id,
                mold_component: { id: a.data.mold_component.id, name: a.data.mold_component.name },
                mes_processes_id: pitem.mes_processes_id,
                mes_processes: { id: pitem.mes_processes_id, name: pitem.mes_processes.name },
              })

            });
            this.detailsData2 = [...this.detailsData2, ...currentAddRows];
          }

          if (index + 1 < component_ids.length) {
            loadNextComponent(index + 1);
          } else {
            this.detailsData2 = JSON.parse(JSON.stringify(this.detailsData2))
            this.detailsDataInit();

            console.log(JSON.stringify(this.detailsData2))

          }
        });
      };

      if (component_ids.length) {
        loadNextComponent(0);
      }

    },



    // 保存
    ok() {



      let save = () => {


        // 如果是新增模式，提交新增接口 如果是编辑模式，提交编辑接口
        let action = !this.isEdit ? this.actions.create : this.actions.update;
        // 如果是新增模式，提交的数据中加入id 如果是编辑模式，提交的数据中不加入id
        let postdata = Object.assign({}, this.formOptions.data);

        console.log(postdata)

        // 格式化提交的数据
        this.$mk.formatFormData({ data: postdata, rules: this.formOptions.items });

        postdata.mold_scheme_components = this.$mk.getPostFieldValue({
          rowFilter: (row) => { return row.id || row.component_id },
          dataId: this.getDataId_BigInt(),
          list: this.detailsData,
          deletedList: this.deletedDetailsData,
          fieldName: 'mold_id',
          dataRule: [
            { field: 'production_type', type: 'integer' },
            { field: 'id', type: 'bigint' },
            { field: 'update_uid', type: 'bigint' },
            { field: 'component_id', type: 'bigint' },
            { field: 'create_uid', type: 'bigint' },
            { field: 'process_uid', type: 'bigint' },


          ]
        });


        postdata.mold_scheme_processes = this.$mk.getPostFieldValue({
          rowFilter: (row) => { return row.id || (row.component_id && row.mes_processes_id) },
          dataId: this.getDataId_BigInt(),
          list: this.detailsData2,
          deletedList: this.deletedDetailsData2,
          fieldName: 'mold_id',
          dataRule: [
            { field: 'id', type: 'bigint' },
            { field: 'update_uid', type: 'bigint' },
            { field: 'component_id', type: 'bigint' },
            { field: 'mes_processes_id', type: 'bigint' },

            
            { field: 'create_uid', type: 'bigint' }
          ]
        });

        // 提交数据
        this.$mk.post({
          url: action,
          loading: "保存中...",
          data: postdata,
          useBigInt: true,
        }).then((a) => { // 成功回调
          if (a.code == "200") {


            this.$mk.success("保存成功");
            if (!this.isEdit) { // 如果是新增模式，关闭当前页面
              this.back();
            }

          } else {
            this.$mk.error(a.message);
          }


        });


      };





      // 验证表单
      this.$mk.validateForm({ form: this.$refs.xForm }).then(() => { // 验证表单

        save(); // 提交保存

      }).catch(count => { // 验证失败
        this.$mk.error(`存在${count}项错误，请检查`);
      });


    },


    // 取消 返回
    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) {
      if (this.detailsData.length == 1) {
        this.$mk.success("至少保留一行");
        return;
      }
      const $table = this.$refs.xTable;
      if (row.id) {
        this.deletedDetailsData.push(this.$mk.toBigInt(row.id))
      }
      this.detailsData.splice($table.getRowSeq(row) - 1, 1);
    },


    pageAdd2(row) {
      const $table = this.$refs.xTable2
      const record = {
      }
      if (row) {
        this.detailsData2.splice($table.getRowSeq(row), 0, record);
      } else {
        this.detailsData2.push(record)
      }
    },
    pageDelete2(row) {
      if (this.detailsData2.length == 1) {
        this.$mk.success("至少保留一行");
        return;
      }
      const $table = this.$refs.xTable2;
      if (row.id) {
        this.deletedDetailsData2.push(this.$mk.toBigInt(row.id))
      }
      this.detailsData2.splice($table.getRowSeq(row) - 1, 1);
    },



    beforeEditMethod({ column, row }) {
      console.log(column, row);
      return true;
    },
    afterEditEvent({ column, row }) {
      console.log(column, row);
    },
    beforeEditEvent({ column, row }) {
      console.log(column, row);
    },
    onPulldownSelected({ row, name, params }) {
      console.log(row, name, params);

    },
    onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
    },


  },
  // 监听属性
  watch: {

  }
};

</script>


<style scoped lang="less">
.page-body {
  padding: 30px;
  background: @base-bg-color;
}

.formtabs .ant-tabs-tabpane {
  /* background: white; */
  padding: 12px;
}

.gridPanel {
  height: calc(100vh - 600px);
}

.footerbar {
  padding-left: 10px;
}

.imagePanel {
  cursor: pointer;
  padding: 10px;
  width: 100px;

  img {
    width: 80px;
    height: 80px;
  }
}

.oplinks2 svg {
  width: 18px;
  height: 18px;
}

.oplinks2 i {
  margin-left: 5px;
}</style>
