<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addRepairNotesDialog"
    :title="title"
    :close-on-click-modal="false"
    width="85%"
    :maxable="true"
    append-to-body
    @close="handleClose"
  >
    <!-- :fullscreen="fullscreen" -->
    <info ref="infoRef" :type="type"></info>
    <div slot="footer" class="footer">
      <el-button type="primary" @click="submitAdd" v-if="type != 'view'">保存</el-button>
      <el-button @click="handleClose">返回</el-button>
    </div>
  </ele-modal>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';

import modalTitle from '@/BIZComponents/modalTitle.vue';
import customerDialog from '@/views/financialManage/components/customerListDialog.vue';

import {
  saveSalesDemand,
  updateSalesDemand,
  getSalesDemandById
} from '@/api/salesServiceManagement/index';

import fileMain from '@/components/addDoc/index.vue';
import info from '@/views/salesServiceManagement/components/info.vue';

export default {
  components: {
    modalTitle,
    customerDialog,
    fileMain,
    info
  },
  watch: {},
  computed: {
    ...mapGetters(['getDictValue'])
  },
  data() {
    return {
      title: '新增',
      addRepairNotesDialog: false,
      type: 'add',
      form: {}
    };
  },
  created() {},
  methods: {
    // 初始化数据(父组件调用)
    init(row, type) {
      this.addRepairNotesDialog = true;
      this.type = type;
      this.title = type == 'add' ? '新增' : type == 'view' ? '详情' : '修改';
      if (row?.id) {
        this.getDetail(row.id);
      } else {
      }
    },
    async getDetail(id) {
      const res = await getSalesDemandById(id);
      this.$nextTick(() => {
        this.$refs.infoRef.init(res);
      });

      this.form = res;
    },

    handleClose() {
      this.addRepairNotesDialog = false;
      this.form = {};
      this.$refs.infoRef.catch();
    },
    // 标准时间函数 ***
    formatDate(dateString) {
      const isStandardFormat = /^\d{4}-\d{1,2}-\d{1,2}$/.test(dateString);
      if (isStandardFormat) {
        return dateString;
      }
      try {
        const date = new Date(dateString);
        if (isNaN(date.getTime())) {
          throw new Error('Invalid date');
        }
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      } catch (error) {
        return dateString; // 转换失败时返回原始字符串
      }
    },
    async submitAdd() {
      let data = this.$refs.infoRef.getValue();
      if (!data.contactInfoVOS?.length) {
        this.$message.warning('联系人信息至少有1条');
        return;
      }
      try {
        let valid = await this.$refs.infoRef.getValidate();
        let expectedTime = data.expectedTime
          ? this.formatDate(data.expectedTime)
          : '';
        let pData = {
          ...this.form,
          name: data.name,
          faultLevel: data.faultLevel,
          expectedTime: expectedTime,
          contactId: data.contractInfo.id,
          contactCode: data.contractInfo.code,
          contactName: data.contractInfo.name,
          orderCode: data.orderCode,
          orderId: data.orderId,
          contactAddress: data.contactAddress,
          productDetail: data.tableList.map((item) => {
            item['produceTime'] = item['produceTime'] || null;
            return item;
          }),
          contactInfoVOS: data.contactInfoVOS
        };
        let requestname =
          this.title === '新增' ? saveSalesDemand : updateSalesDemand;
        const res = await requestname(pData);
        if (res) {
          this.$message.success('操作成功!');
          this.$emit('refresh');
          this.handleClose();
        }
      } catch (error) {}
    }
  }
};
</script>

<style lang="scss" scoped>
.dialog_top {
  margin-bottom: 10px;
  display: flex;
  align-items: center;

  span {
    margin-left: 50px;
  }

  .name {
    font-weight: 800;
    color: #40a9ff;
  }
}

::v-deep .el-row {
  display: flex;
  flex-wrap: wrap;
}

.btns {
  text-align: right;
  // margin: 10px 0;
}

.main_container {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>
