<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>
      <!--  =========================== 自定义区域 Start  ======================= -->

      <!--  =========================== 自定义区域 End  ======================= -->
    </vxe-form>

    <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/Middle/transport/Maintenance/api.js';
// import PageLayout from '@/layouts/PageLayout'


export default {

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

  },

  data() {

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

      uploadDefaultImg: null,
      detailDataFieldName: "maintenance",

      actions: {
        // =============================== 接口地址 自动生成 Start ===============================
        LogList: `${BASE_URL.BASE_URL}/Maintenance/v1/log/list`, // 操作日志列表
        LogDetail: `${BASE_URL.BASE_URL}/Maintenance/v1/log/detail`, // 操作日志详情
        MaintenanceGiornaleLogList: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/list`, // 维修记录列表
        MaintenanceGiornaleLogSearch: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/search`, // 维修记录搜索
        MaintenanceGiornaleLogDetail: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/detail`, // 维修记录详情
        MaintenanceGiornaleLogCreate: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/create`, // 创建维修记录
        MaintenanceGiornaleLogUpdate: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/update`, // 更新维修记录
        MaintenanceGiornaleLogDelete: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/detele`, // 删除维修记录
        MaintenanceGiornaleLogBatchDelete: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/batchDelete`, // 批量删除维修记录
        MaintenanceGiornaleLogBatchUpdate: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/batchUpdate`, // 批量更新维修记录
        MaintenanceGiornaleLogBatchCreate: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/batchCreate`, // 批量创建维修记录
        MaintenanceGiornaleLogBatchHandle: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/batchHandle`, // 批量处理维修记录
        MaintenanceGiornaleLogAbolish: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/giornale/log/abolish`, // 维修记录作废
        OtherExpensesLogList: `${BASE_URL.BASE_URL}/Maintenance/v1/other/expenses/log/list`, // 其他费用列表
        OtherExpensesLogSearch: `${BASE_URL.BASE_URL}/Maintenance/v1/other/expenses/log/search`, // 其他费用搜索
        OtherExpensesLogDetail: `${BASE_URL.BASE_URL}/Maintenance/v1/other/expenses/log/detail`, // 其他费用详情
        OtherExpensesLogCreate: `${BASE_URL.BASE_URL}/Maintenance/v1/other/expenses/log/create`, // 创建其他费用
        OtherExpensesLogUpdate: `${BASE_URL.BASE_URL}/Maintenance/v1/other/expenses/log/update`, // 更新其他费用
        OtherExpensesLogDelete: `${BASE_URL.BASE_URL}/Maintenance/v1/other/expenses/log/detele`, // 删除其他费用
        OtherExpensesLogBatchDelete: `${BASE_URL.BASE_URL}/Maintenance/v1/other/expenses/log/batchDelete`, // 批量删除其他费用
        OtherExpensesLogBatchUpdate: `${BASE_URL.BASE_URL}/Maintenance/v1/other/expenses/log/batchUpdate`, // 批量更新其他费用
        OtherExpensesLogBatchCreate: `${BASE_URL.BASE_URL}/Maintenance/v1/other/expenses/log/batchCreate`, // 批量创建其他费用
        OtherExpensesLogBatchHandle: `${BASE_URL.BASE_URL}/Maintenance/v1/other/expenses/log/batchHandle`, // 批量处理其他费用

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

      keyName: 'id',
      // 是否编辑模式
      isEdit: false,
      // 表单数据
      formOptions: {
        data: {
          // =============================== 表单数据 自动生成 Start ===============================

          id: 0,
          truck_number_id: 0,
          truck_number_code: "",
          truck_id: 0,
          truck_code: "",
          truck_name: "",
          truck_number: "",
          maintenance_id: 0,
          maintenance_name: "",
          maintenance_date: new Date(2100, 1, 1).getTime() / 10000,
          maintenance_price: 0,
          maintenance_remark: "",
          create_uid: 0,
          update_uid: 0,
          create_time: new Date(2100, 1, 1).getTime() / 10000,
          update_time: new Date(2100, 1, 1).getTime() / 10000,
          other_expenses_amount: 0,

          // =============================== 表单数据 自动生成 End ===============================
        },
        // 标题宽度
        titleWidth: 100,
        // 标题对齐方式
        titleAlign: 'right',

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

          truck_number_id: [
            { message: '请输入车次id' }
          ],
          truck_number_code: [
            { message: '请输入车次单号' }
          ],
          truck_id: [
            { message: '请输入车辆id' }
          ],
          truck_code: [
            { message: '请输入车辆编码' }
          ],
          truck_name: [
            { message: '请输入车辆名称' }
          ],
          truck_number: [
            { message: '请输入车牌号' }
          ],
          maintenance_id: [
            { message: '请输入维修项目' }
          ],
          maintenance_date:[
            { message: '请输入维修日期' }
          ],
          maintenance_remark: [
            { message: '请输入维修备注' }
          ],
          maintenance_price: [
            { message: '请输入维修金额' }
          ],

          // =============================== 表单校验 自动生成 End ===============================
        },
        // 表单项
        items: [
          // =============================== 表单项 自动生成 Start ===============================

          {
            title: '车辆', span: 6,
            field: 'Truck',
            dataRule: {
              fromField: "name",
              saveField: "name"
            },
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "id",
                  textField: "name",
                  listdataFieldName: 'Truck',
                  dataUrl: `${BASE_URL.BASE_URL}/Truck/v1/truck/list`,
                  onDataChanged: ({ data }) => {
                    console.log(data)
                    this.formOptions.data.truck_id = data.id;
                    this.formOptions.data.truck_code = data.code;
                    this.formOptions.data.truck_name = data.name;
                    this.formOptions.data.truck_number = data.plate_number;
                  }
                }
              }
            }
          },
          {
            title: '维修项目', span: 6,
            field: 'Maintenance',
            dataRule: {
              fromField: "name",
              saveField: "name"
            },
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "id",
                  textField: "name",
                  listdataFieldName: 'Maintenance',
                  dataUrl: `${BASE_URL.BASE_URL}/Maintenance/v1/maintenance/list`,
                  onDataChanged: ({ data }) => {
                    console.log(data)
                    this.formOptions.data.maintenance_id = data.id;
                  }
                }
              }
            }
          },
          { field: 'maintenance_date', dataRule: { type: 'timestamp' }, title: '维修日期', span: 6, itemRender: { name: '$input', props: { type: "date" } } },
          {
            field: 'maintenance_price', title: '维修金额', span: 6, itemRender: {
              name: '$input', props: { type: 'number' }
            }
          },
          { field: 'maintenance_remark', title: '维修备注', span: 24, itemRender: { name: '$textarea' } },


          // =============================== 表单项 自动生成 End ===============================
        ]
      },
      // 新增模式表单项
      addModeItems: [],


    };

    pageData.actions.get = pageData.actions.MaintenanceDetail;
    pageData.actions.create = pageData.actions.MaintenanceCreate;
    pageData.actions.update = pageData.actions.MaintenanceUpdate;

    // 合并表单数据及配置
    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) {
      const json = `{"id":${dataId}}`;
      this.$mk.post({
        url: this.actions.get,
        loading: "加载中...",
        data: json,
        config: {
          headers: {
            'Content-Type': 'application/json'
          }
        }
      }).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;
    } else {
      // 如果没有id参数，说明是新增模式
      this.addModeItems.forEach(item => {
        this.formOptions.items.push(item);
      })

    }

  },
  // 函数
  methods: {


    // 获取路由的id参数
    getDataId() {
      let dataId = this.dataId;
      if (this.$route.params.id) {
        dataId = this.$route.params.id;
      }
      if (!dataId) {
        dataId = 0;
      }
      return dataId;
    },


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

    // 保存
    ok() {

      let save = () => {

         // this.formOptions.data.maintenance_price 转换为数字

         this.formOptions.data.maintenance_price = Number(this.formOptions.data.maintenance_price);
        // 如果是新增模式，提交新增接口 如果是编辑模式，提交编辑接口
        let action = !this.isEdit ? this.actions.MaintenanceGiornaleLogCreate : this.actions.MaintenanceGiornaleLogUpdate;
        // 如果是新增模式，提交的数据中加入id 如果是编辑模式，提交的数据中不加入id
        let postdata = Object.assign({}, this.formOptions.data);
        // 如果是编辑模式
        if (this.isEdit) {
          // postdata = { MaintenanceGiornaleLog: postdata }
        }
        // 格式化提交的数据
        this.$mk.formatFormData({ data: postdata, rules: this.formOptions.items });


        // 提交数据
        this.$mk.post({
          url: action,
          loading: "保存中...",
          data: postdata,
          useBigInt: true,
        }).then(() => { // 成功回调
          this.$mk.success("保存成功");
          if (!this.isEdit) { // 如果是新增模式，关闭当前页面
            this.back();
            this.$forceUpdate()
          }
        }).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();
    }
  },
  // 监听属性
  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>
