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

    <a-tabs v-model="tabKey" hide-add>
      <a-tab-pane key="1" tab="基础信息">

        <vxe-form :data="options.formOptions.data" ref="xForm" :title-width="options.formOptions.titleWidth"
          :title-align="options.formOptions.titleAlign" :rules="options.formOptions.rules"
          :items="options.formOptions.items" titleColon>
          <template #sort_id="{}">
            <vxe-pulldown style="width:100%" ref="pulldownParent" transfer>
              <template #default>
                <vxe-input v-model="sortName" suffix-icon="vxe-icon-search" placeholder="选择分类" @keyup="pulldownKeyupEvent"
                  @focus="pulldownFocusEvent" @suffix-click="pulldownSuffixClick"></vxe-input>
              </template>
              <template #dropdown>
                <div class="my-dropdown">
                  <vxe-grid ref="gridParent" v-bind="gridParentOptions" @cell-click="pulldownCellClickEvent">
                  </vxe-grid>
                </div>
              </template>
            </vxe-pulldown>
          </template>
        </vxe-form>

      </a-tab-pane>
      <a-tab-pane key="2" tab="料品属性">

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



      </a-tab-pane>
    </a-tabs>



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

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

  data() {

    let pageData = {
      actions: {
        list: `${BASE_URL.BASE_URL}/MesMaterials/v1/mes/materials/sort/list`,
      },
      tabKey: '1',
      sortName: '',
      custom_attribute_value: [],
      attributes: [],
      gridParentOptions: {
        height: 400,
        id: 'datagrid_router_parent_1',

        proxyConfig: {
          sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
          filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为 
          props: {
            result: 'MesMaterialsSort', // 配置响应结果列表字段
            total: 'total' // 配置响应结果总页数字段
          },
          // 接收Promise
          ajax: {
            // 当点击工具栏查询按钮或者手动提交指令 query或reload 时会被触发
            query: (options) => {
              const { page, sorts } = options;
              var params = {};
              params.page = page.currentPage;
              params.limit = page.pageSize;
              params.order_bys = [];
              params.search_rules = [];
              if (sorts) {
                sorts.forEach((v) => {
                  params.order_bys.push({
                    column: v.property,
                    order: v.order
                  })
                });
              }
              return this.loadParentGrid({ params });
            }
          }
        },
        sortConfig: {
        },
        treeConfig: {
          transform: true,
          expandAll: true,
          rowField: 'id',
          parentField: 'parent_id'
        },
        checkboxConfig: {
          reserve: true,
          highlight: true
        },
        columns: [
          { field: 'name', sortable: true, title: '分类名', showHeaderOverflow: true, treeNode: true },
          { field: 'code', sortable: true, title: '编号', showHeaderOverflow: true }
        ]
      },
      options: {}
    };

    pageData.gridParentOptions = Object.assign({}, this.$mk.config.defaults.gridOptions, pageData.gridParentOptions);
    return pageData;
  },

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


  created() {

    this.optionsInit();
    this.dataInit();

  },
  // 函数
  methods: {


    loadParentGrid({ params }) {


      params.start_time = 0;
      params.end_time = 0;

      return this.$mk.getPagedData({ url: this.actions.list, data: params });
    },
    optionsInit() {
      // 页面数据变量
      var pageData = {
        // 当前项目名称
        currentConfigName: "",
        // 当前项目ID
        currentBeid: 0,

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


        uploadDefaultImg: null,
        detailDataFieldName: "mes_materials",

        actions: {
          // =============================== 接口地址 自动生成 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 ===============================


          productAttribute: `${BASE_URL.BASE_URL}/MesProductCustomAttribute/v1/get/productAttribute`
        },

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

          // 表单校验规则
          rules: {
            // =============================== 表单校验 自动生成 Start ===============================

            code: [
              { required: true, message: '请输入编号' }
            ],
            name: [
              { required: true, message: '请输入名称' }
            ]

            // =============================== 表单校验 自动生成 End ===============================
          },
          // 表单项
          items: [
            { field: 'code', title: '编号', span: 12, itemRender: { name: '$input' } },
            { field: 'name', title: '名称', span: 12, itemRender: { name: '$input' } },

            { title: '分类', span: 12, slots: { default: 'sort_id' } },

            { field: 'spec', title: '规格型号', span: 12, itemRender: { name: '$input' } },
            { field: 'size', title: '尺寸', span: 12, itemRender: { name: '$input' } }, 

            {
            title: '颜色', span: 12,
            field: 'color', 
            itemRender: { 
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'MesEnumValue',
                  actionParams:{
                    search_rules_enum: [
                      {
                        column:"code",
                        mode:"=",
                        value:"3"
                      } 
                    ]
                  },
                  dataUrl: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/list`
                }
              }
            }
          },
 
            {
            title: '花面', span: 12,
            field: 'face', 
            itemRender: { 
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'MesEnumValue',
                  actionParams:{
                    search_rules_enum: [
                      {
                        column:"code",
                        mode:"=",
                        value:"4"
                      } 
                    ]
                  },
                  dataUrl: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/list`
                }
              }
            }
          },
            {
            title: '成型方式', span: 12,
            field: 'molding', 
            itemRender: { 
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'MesEnumValue',
                  actionParams:{
                    search_rules_enum: [
                      {
                        column:"code",
                        mode:"=",
                        value:"1"
                      } 
                    ]
                  },
                  dataUrl: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/list`
                }
              }
            }
          },

          
          {
            title: '布产方式', span: 12,
            field: 'production_type', 
            itemRender: { 
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'MesEnumValue',
                  actionParams:{
                    search_rules_enum: [
                      {
                        column:"code",
                        mode:"=",
                        value:"2"
                      } 
                    ]
                  },
                  dataUrl: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/list`
                }
              }
            }
          },
 

            { field: 'theoretical_load', title: '理论装车量', span: 12, itemRender: { name: '$input' } },
 
            {
            title: '土质', span: 12,
            field: 'soil', 
            itemRender: { 
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'MesEnumValue',
                  actionParams:{
                    search_rules_enum: [
                      {
                        column:"code",
                        mode:"=",
                        value:"5"
                      } 
                    ]
                  },
                  dataUrl: `${BASE_URL.BASE_URL}/MesEnum/v1/mes/enum/value/list`
                }
              }
            }
          },
            {
            title: '单位', span: 12,
            field: 'unit', 
            itemRender: { 
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'MesUnit',
                  dataUrl: `${BASE_URL.BASE_URL}/MesUnit/v1/mes/unit/list`
                }
              }
            }
          },


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

        ],

        formOptions2Done: false,
        formOptions2: {
          data: {

          },
          // 标题宽度
          titleWidth: 150,
          // 标题对齐方式
          titleAlign: 'right',

          // 表单校验规则
          rules: {

          },
          // 表单项
          items: [

          ]
        },


      };

      pageData.formOptions.items.forEach(item => {

        pageData.formOptions.data[item.field] = '';
      })
      pageData.actions.get = pageData.actions.MesMaterialsDetail;
      pageData.actions.create = pageData.actions.MesMaterialsCreate;
      pageData.actions.update = pageData.actions.MesMaterialsUpdate;

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

      this.options = pageData;
    },


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

        let getOptions = (id) => {

          let options = [];
          a.data.field.forEach(fieldItem => {
            if (fieldItem.attribute_id.toString() == id.toString()) {
              options.push({
                value: fieldItem.id.toString(),
                label: fieldItem.name
              })
            }
          })
          return options
        }

        this.attributes = a.data.attribute;

        let formData = {};
        a.data.attribute.forEach(item => {

          let formItem = { field: '', title: '', span: 12, itemRender: {} };

          formItem.field = "attr" + item.id;
          formItem.title = item.name;
          //属性类型:1.文本,2.数字,3.日期,4.时间,5.日期时间,6.单选,7.布尔
          if (item.typeName == "2") {
            formItem.itemRender.props = { type: "nubmer" };

            formItem.itemRender.name = "$input";
            formData[formItem.field] = 0;
          }
          else if (item.typeName == "3" ||
            item.typeName == "4" ||
            item.typeName == "5") {

            formItem.itemRender.name = "$input";
            formItem.itemRender.props = { type: "date" };

            formData[formItem.field] = '';
          }
          else if (item.typeName == "6") {
            formItem.itemRender.name = "$select";
            formItem.itemRender.options = getOptions(item.id);
            if (!formItem.itemRender.options.length) {
              return;
            }
            formData[formItem.field] = formItem.itemRender.options[0].value;
          }
          else if (item.typeName == "7") {
            formItem.itemRender.name = "$switch";
            formItem.itemRender.props = { openLabel: '是', openValue: "true", closeValue: "false", closeLabel: '否' };

            formData[formItem.field] = '1';
          } else {

            formItem.itemRender.name = "$input";
            formData[formItem.field] = '';
          }

          let ov = this.getOldAttributeValue(item.id);
          if(ov !== null){
            formData[formItem.field] = ov;
          }

          this.options.formOptions2.items.push(formItem);
        })
        this.options.formOptions2.data = formData; 


        this.options.formOptions2Done = true;
        this.$forceUpdate();

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

    dataInit() {


      


      // 获取路由的id参数
      let dataId = this.getDataId();
      // 如果有id参数，说明是编辑模式
      if (dataId) {
        const json = `{"id":${dataId}}`;
        this.$mk.post({
          url: this.options.actions.get,
          loading: "加载中...",
          data: json,
          config: {
            headers: {
              'Content-Type': 'application/json'
            }
          }
        }).then(a => {

          let detailDataFieldName = this.options.detailDataFieldName;

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


          this.options.formOptions.data = a.data[detailDataFieldName];

          this.custom_attribute_value = a.data[detailDataFieldName].custom_attribute_value || [];

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

        this.options.isEdit = true;

        this.$forceUpdate()
      }  else{
        
        this.attributeDataInit();
      }
    },

    getOldAttributeValue(attribute_id) {
      for(let i =0;i<this.custom_attribute_value.length;i++){
        if(this.custom_attribute_value[i].attribute_id.toString() == attribute_id.toString()){
          return this.custom_attribute_value[i].value;
        }
      }
      return null;

    },
    getAttributeValue(attribute_id) {
      return this.options.formOptions2.data["attr" + attribute_id.toString()];

    },

    // 获取路由的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() {
      this.isEdit = this.options.isEdit;
      // 如果是新增模式，关闭当前页面
      if (!this.isEdit) {
        this.$closePage({
          closeRoute: this.options.addPageUrl
        });
      } else {
        this.$closePage({
          closeRoute: this.options.editPageUrl
        });
      }
      // 打开列表页面
      this.$openPage(this.options.listPageUrl)
    },

    // 保存
    ok() {

      let save = () => {

        this.isEdit = this.options.isEdit;

        // 如果是新增模式，提交新增接口 如果是编辑模式，提交编辑接口
        let action = !this.isEdit ? this.options.actions.create : this.options.actions.update;


        // 如果是新增模式，提交的数据中加入id 如果是编辑模式，提交的数据中不加入id
        let postdata = Object.assign({}, this.options.formOptions.data);
        // 如果是编辑模式
        if (this.isEdit) {
          // postdata = { MesUnit: postdata }
        }


        postdata.custom_attribute_value = [];

        let findOldAttribute = (id) => {

          let attrs = this.custom_attribute_value.filter(a => a.attribute_id.toString() == id.toString());
          if (attrs.length) {
            return attrs[0]
          }
          return null;

        }
        this.attributes.forEach(item => {

          let v = this.getAttributeValue(item.id);
          let old = findOldAttribute(item.id);
          if (old != null) {
            old.value = v;
            old.e_value = v;
            postdata.custom_attribute_value.push(old);
          } else {

            let newItem = {
              attribute_id: item.id,
              "value": v,
              "e_value": v
            };
            if (this.isEdit) {
              newItem.product_id = this.getDataId_BigInt();
            }
            postdata.custom_attribute_value.push(newItem)
          }


        })

        delete postdata.create_time
        delete postdata.create_uid
        delete postdata.update_time
        delete postdata.update_uid
        delete postdata.custom_attribute_attribute
        delete postdata.custom_attribute_category
        delete postdata.custom_attribute_field 
        delete postdata.mes_materials_sort

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


        // 提交数据
        this.$mk.post({
          url: action,
          loading: "保存中...",
          data: postdata,
          useBigInt: true,
        }).then(() => { // 成功回调
          this.$mk.success("保存成功");
          if (!this.isEdit) { // 如果是新增模式，关闭当前页面
            this.back();
          }
        }).catch((a) => { // 失败回调
          this.$mk.error(a.data.msg); // 显示错误信息
        });


      };


      // 验证表单
      this.$mk.validateForm({ form: this.$refs.xForm }).then(() => { // 验证表单
        save(); // 提交保存
      }).catch(count => { // 验证失败
        this.$mk.error(`存在${count}项错误，请检查`);
      });


    },


    // 取消 返回
    cancel() {
      this.back();
    },

    pulldownFocusEvent() {
      this.$refs.pulldownParent.showPanel()
    },
    pulldownKeyupEvent() {

    },
    pulldownSuffixClick() {
      this.$refs.pulldownParent.togglePanel()
    },
    pulldownCellClickEvent({ row }) {

      if (row.children && row.children.length) {
        return;
      }
      this.options.formOptions.data.sort_id = row.id;
      this.sortName = row.name;
      this.$refs.pulldownParent.hidePanel()

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