<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 v-if="formOptions.data.typeName == '6'" 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="name" title="属性选项" width="120" :edit-render="{ name: '$input', props: {} }">
      </vxe-column>
      <vxe-column field="code" title="编码" width="120" :edit-render="{ name: '$input', props: {} }">
      </vxe-column>
      <vxe-column field="e_name" title="属性选项(英文)" width="120" :edit-render="{ name: '$input', props: {} }">
      </vxe-column>
      <vxe-column field="description" title="描述" width="120" :edit-render="{ name: '$input', props: {} }">
      </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';
const settings = require('../../basic/settings.js');

export default {

  name: 'BathroomPartsUpdate',
  i18n: require('./i18n'),
  components: {},
  props: {
    pageMode: {
      type: String,
      default: "edit"
    },
    dataId: {
    }

  },

  data() {

    //let _this = this;
    // 页面数据变量
    var pageData = {
      // 当前项目名称
      currentConfigName: "",
      // 当前项目ID
      currentBeid: 0,

      uploadDefaultImg: null,
      detailDataFieldName: "attribute",

      actions: {
        get: `${BASE_URL.BASE_URL}/MesProductCustomAttribute/v1/attribute/detail`,
        create: `${BASE_URL.BASE_URL}/MesProductCustomAttribute/v1/attribute/create`,
        update: `${BASE_URL.BASE_URL}/MesProductCustomAttribute/v1/attribute/update`,
        detailsData: `${BASE_URL.BASE_URL}/MesProductCustomAttribute/v1/field/list`,
        saveDetails: `${BASE_URL.BASE_URL}/MesProductCustomAttribute/v1/field/batchHandle`,
      },

      keyName: 'id',
      // 是否编辑模式
      isEdit: false,
      // 表单数据
      formOptions: {
        data: {
          name: '',
          typeName: '1'
        },
        // 标题宽度
        titleWidth: 140,
        // 标题对齐方式
        titleAlign: 'right',

        // 表单校验规则
        rules: {

          name: [
            { required: true, message: '请输入属性名称' }
          ],
          category: [
            { required: true, message: '请选择分类' }
          ]

        },
        // 表单项
        items: [

          { field: 'name', title: '属性名称', span: 8, itemRender: { name: '$input' } },
          { field: 'e_name', title: '属性名称(英文)', span: 8, itemRender: { name: '$input' } },
          { field: 'code', title: '编码', span: 8, itemRender: { name: '$input' } },
          {
            title: '分类', span: 8,
            field: 'category',
            dataRule: {
              fromField: "id",
              saveField: "category_id" // 如果表单项存储的是对象，将从fromField中取得值保存到saveField
            },
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "object",
                  valueField: "id",
                  textField: "name",
                  listdataFieldName: 'Category',
                  dataUrl: `${BASE_URL.BASE_URL}/MesProductCustomAttribute/v1/category/list`
                }
              }
            }
          },

          { field: 'typeName', title: '属性类型', span: 8, itemRender: { name: '$select', props: { options: settings.options_attribute_types } } },
        ]
      },
      // 新增模式表单项
      addModeItems: [

      ],


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

      ],
      editorMaterials: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesMaterials',
        dataUrl: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/list`
      },
      editorWarehouse: {
        dataType: "object",
        valueField: "id",
        textField: "warehouse_name",
        listdataFieldName: 'MesWarehouse',
        searchFieldNames: ['warehouse_name'],
        columns: [ // 表格列
          { field: 'warehouse_name', title: '名称' },   // 字段名称，字段标题
          { field: 'code', title: '编码' }   // 字段名称，字段标题
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MesWarehouse/v1/mes/warehouse/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 => {
        // =============================== 时间字段判断 自动生成 Start ===============================

        if (a.data[this.detailDataFieldName].create_time) {
          a.data[this.detailDataFieldName].create_time = new Date(a.data[this.detailDataFieldName].create_time * 1000);
        }
        if (a.data[this.detailDataFieldName].update_time) {
          a.data[this.detailDataFieldName].update_time = new Date(a.data[this.detailDataFieldName].update_time * 1000);
        }

        // =============================== 时间字段判断 自动生成 End ===============================
        this.formOptions.data = a.data[this.detailDataFieldName];

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

      this.isEdit = true;

      this.detailsDataLoad(dataId);

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

      this.detailsDataInit();
    }



    this.heightInit();

  },
  // 函数
  methods: {



    detailsDataLoad(id) {

      this.$mk.post({
        url: this.actions.detailsData,
        loading: "加载中...",
        data: {
          "page": 1,
          "limit": 10000,
          "start_time": 0,
          "end_time": 0,
          "search_rules": [
            {
              column: "attribute_id", // 字段名
              mode: "=", // 搜索模式
              value: id.toString()
            }
          ],
          "order_bys": [
          ]
        },
        useBigInt: true
      }).then(a => {

        this.detailsSourceData = a.data.Field || [];
        this.detailsData = JSON.parse(JSON.stringify(a.data.Field || []));

        this.detailsDataInit();
      });
    },

    heightInit() {

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

        this.table1Height = h;
      });

    },
    detailsDataInit() {
      for (let i = 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: "/MesProductCustomAttribute/MesProductCustomAttributeAdd"
        });
      } else {
        // 如果是编辑模式，关闭当前页面
        this.$closePage({
          closeRoute: "/MesProductCustomAttribute/MesProductCustomAttributeUpdate"
        });
      }
      // 打开列表页面
      this.$openPage('/MesProductCustomAttribute/MesProductCustomAttributeList')
    },



    // 保存
    ok() {




      let saveDetails = (dataId) => {

        dataId = dataId || this.getDataId_BigInt();
        let ds = [];

        this.detailsData.forEach(item => {
          if (item.name) {
            let o = Object.assign({}, item);
            if (item.id) {
              o.id = this.$mk.toBigInt(item.id);
            }
            ds.push(o);
          } 
        });
 
console.log(this.formOptions.data)
        var postdata = {
          insertList: [],
          updateList: [],
          deleteList: this.deletedDetailsData
        };

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

          item.attribute_id = dataId;
          if(this.formOptions.data.category_id){
            item.category_id = this.formOptions.data.category_id;
          }else if(this.formOptions.data.category && this.formOptions.data.category.id){
            item.category_id = this.formOptions.data.category.id;

          }
         
          if (item.id) {
            postdata.updateList.push(item);
          } else {
            postdata.insertList.push(item);
          }
        })
        this.$mk.post({
          url: this.actions.saveDetails,
          data: postdata,
          useBigInt: true
        }).then(a => {
          if (a.code == "200") {

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

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


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


        // 如果是新增模式，提交新增接口 如果是编辑模式，提交编辑接口
        let action = !this.isEdit ? this.actions.create : this.actions.update;
        // 如果是新增模式，提交的数据中加入id 如果是编辑模式，提交的数据中不加入id
        let postdata = Object.assign({}, this.formOptions.data);
        // 如果是编辑模式
        if (this.isEdit) {
          // postdata = { BathroomParts: postdata }
        }
        // 格式化提交的数据
        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") {


            saveDetails(a.data.id);

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


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


      };





      // 验证表单
      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 }) {

      if (row.SourceTableID && column.field != "Quantity") {
        return false;
      }
      return true;
    },
    afterEditEvent({ column, row }) {
      if (column.field == "Quantity" || column.field == "Price") {
        row.Amount = parseInt(row.Quantity || 0) * parseFloat(row.Price || 0);

      }

      if (column.field == "specification") {
        row.specification = this.specification;
      }
    },
    beforeEditEvent({ column, row }) {
      if (row.SourceTableID && column.field != "Quantity") {
        return false;
      }
      if (column.field == "specification") {
        this.specification = row.specification;
      }
    },

    onPulldownSelected({ row, name, params }) {
      if (name == 'ag_inventory') {
        this.updateToGrid(row, this.detailsData[params.$rowIndex]);

        setTimeout(() => {
          this.$refs.xTable.clearEdit();
        }, 50);
      }

    },
    onPopupSelected({ rows, name, params }) {
      console.log(rows, name, params);
      if (name == 'ag_inventory') {

        for (let i = params.$rowIndex, ri = 0; i < params.$rowIndex + rows.length; i++, ri++) {
          if (i == this.detailsData.length) {
            let newrow = {
            };
            this.detailsData.push(newrow);
          }
          let inv = rows[ri];

          this.updateToGrid(inv, this.detailsData[i]);
        }

        setTimeout(() => {
          this.$refs.xTable.clearEdit();
        }, 50);


      }

    },
  },
  // 监听属性
  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>
