<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" :demandList="demandList" :type="type"></info>
    <SubmitDialog ref="submitRef" @savExit="savExit" />
    <dispatchDialog ref="dispatchRef" @savExit="savExit" />
    <div slot="footer" class="footer">
      <el-button type="primary" @click="submitAdd" v-if="type != 'view'"
        >保存</el-button
      >
      <el-button type="primary" @click="submit" v-if="type != 'view'"
        >提交</el-button
      >
      <el-button type="primary" @click="dispatch" 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 SubmitDialog from './submitDialog.vue';
  import dispatchDialog from './dispatchDialog.vue';
  import { getByCode } from '@/api/system/dictionary-data';
  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,
      SubmitDialog,
      dispatchDialog
    },
    watch: {},
    computed: {
      ...mapGetters(['getDictValue'])
    },
    data() {
      return {
        title: '新增',
        addRepairNotesDialog: false,
        type: 'add',
        form: {},
        demandList: []
      };
    },
    created() {
      this.getLevelCode('requirement_name');
    },
    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 getLevelCode(code) {
        try {
          const res = await getByCode(code);
          if (res.code == 0) {
            let list = Object.values(res.data).map((el) => {
              let k = Object.keys(el)[0];
              let v = Object.values(el)[0];
              return {
                label: v,
                value: k
              };
            });
            this.demandList = list;
          }
        } catch (err) {
          this.$message.error(err.message);
        }
      },
      // 提交
      async submit() {
        let pData = await this.handleParameter();
        if (!pData) {
          return;
        }
        this.$refs.submitRef.open(pData, this.type);
      },
      // 派单
      async dispatch() {
        let pData = await this.handleParameter();
        if (!pData) {
          return;
        }
        this.$refs.dispatchRef.open(pData, this.type);
      },
      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 handleParameter() {
        let data = this.$refs.infoRef.getValue();
        if (!data.contactInfoVOS?.length) {
          this.$message.warning('联系人信息至少有1条');
          return false;
        }
        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
          };
          return pData;
        } catch (err) {}
      },
      savExit() {
        this.$emit('refresh');
        this.handleClose();
      },
      // 保存
      async submitAdd() {
        // let data = this.$refs.infoRef.getValue();
        // if (!data.contactInfoVOS?.length) {
        //   this.$message.warning('联系人信息至少有1条');
        //   return;
        // }
        try {
          let pData = await this.handleParameter();
          if (!pData) {
            return;
          }
          // 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>
