<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>

    <a-tabs>
      <a-tab-pane key="1" tab="工序设置">

        <vxe-table border show-overflow keep-source ref="xTable" :height="table1Height" :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="mes_processes" title="工序" width="160" :params="editor_processes" formatter="formatRef"
            :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
          <vxe-column field="sort" title="排序" width="160"
            :edit-render="{ name: '$input', props: { type: 'number' } }"></vxe-column>
        </vxe-table>
      </a-tab-pane>

    </a-tabs>


    <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 = {
      // 当前项目名称
      currentConfigName: "",
      // 当前项目ID
      currentBeid: 0,

      uploadDefaultImg: null,
      detailDataFieldName: "mold_component",
      actions: {
        get: `${BASE_URL.BASE_URL}/MoldComponent/v1/mold/component/detail`,
        create: `${BASE_URL.BASE_URL}/MoldComponent/v1/mold/component/create`,
        update: `${BASE_URL.BASE_URL}/MoldComponent/v1/mold/component/update`
      },

      keyName: 'id',
      // 是否编辑模式
      isEdit: false,
      defaultFormData: {
    
        code: '',
          name: '',

      },
      // 表单数据
      formOptions: {
        data: { 
          code: '',
          name: '',
        },
        // 标题宽度
        titleWidth: 100,
        // 标题对齐方式
        titleAlign: 'right',

        // 表单校验规则
        rules: {

          code: [
            { required: true, message: '请输入编码' }
          ],
          name: [
            { required: true, message: '请输入名称' }
          ],
        },
        // 表单项
        items: [
          { field: 'code', title: '编码', span: 12, itemRender: { name: '$input' } },
          { field: 'name', title: '名称', span: 12, itemRender: { name: '$input' } },

          {
            title: '分类', span: 12,
            field: 'mold_component_category',
            dataRule: {
              fromField: "id",
              saveField: "category_id" // 如果表单项存储的是对象，将从fromField中取得值保存到saveField
            },
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "object",
                  valueField: "id",
                  textField: "name",
                  listdataFieldName: 'MoldComponentCategory',
                  dataUrl: `${BASE_URL.BASE_URL}/MoldComponent/v1/mold/component/category/list`
                }
              }
            }
          },

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

      ],


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

      ],
      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`
      },


    };


    // 合并表单数据及配置
    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_component_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) - 180;

        this.table1Height = h;
      });

    },
    detailsDataInit() {
      for (let i = this.detailsData && this.detailsData.length; i < 10; i++) {
        this.detailsData.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/MoldComponentAdd"
        });
      } else {
        // 如果是编辑模式，关闭当前页面
        this.$closePage({
          closeRoute: "/Mold/MoldComponentUpdate"
        });
      }
      // 打开列表页面
      this.$openPage('/Mold/MoldComponent')
    },



    // 保存
    ok() {


      let _this = this;

      let save = () => {


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


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

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


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


            this.$mk.success("保存成功");
            if (!this.isEdit) { // 如果是新增模式，关闭当前页面
              this.$confirm({
                title: '提示',
                content: '新增成功，是否继续',
                okText: '确认',
                cancelText: '返回',
                onOk() {
                  _this.formOptions.data = _this.defaultFormData || {};
                },
                onCancel() {
                  _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) {
      const $table = this.$refs.xTable;
      if (row.id) {
        this.deletedDetailsData.push(this.$mk.toBigInt(row.id))
      }
      this.detailsData.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>
