<template>
  <a-spin :spinning="spinning" tip="加载中...">
    <div class="page-bg-wrap formViewStyle pdcss">
      <div class="top-toolbar" >
        <a-button style="margin-right: 10px" @click="close">
          <slot name="icon"><close-outlined /></slot>关闭
        </a-button>
        <template v-if="currentRoute.query.type!=='compare'">
          <a-button style="margin-right: 10px" type="primary" @click="checkBtn('agree')" v-if="!currentRoute.query.type">
            <slot name="icon"><check-circle-outlined /></slot>通过
          </a-button>
          <a-button style="margin-right: 10px" @click="checkBtn('reject')" v-if="!currentRoute.query.type">
            <slot name="icon"><stop-outlined /></slot>驳回
          </a-button>
        </template>
      </div>
      <a-form ref="formRef" :model="formState" :rules="rules" v-bind="layout">
        <a-row v-if="!currentRoute.query.type">
          <a-col :span="24">
            <a-form-item label="批复意见" name="reply" :label-col="{ span: 3 }" :wrapper-col="{ span: 24 }">
              <a-textarea  v-model:value="formState.reply" :disabled="currentRoute.query.type=='view'"  placeholder="请输入备注"  :auto-size="{ minRows: 2, maxRows: 5 }"/>
            </a-form-item>
          </a-col>
        </a-row>
        <Card :title="title" :bordered="false" >
          <basicForm ref="basicFormRef" :formObj="formState" :list="dataList" :disable="currentRoute.query.type"></basicForm>
        </Card>
        <Card :title="titleNew" :bordered="false" v-if="currentRoute.query.type=='compare'&&titleNew">
          <basicForm ref="basicFormRef" :formObj="formStateNew" :list="dataListNew" :disable="currentRoute.query.type"></basicForm>
        </Card>
      </a-form>
    </div>
  </a-spin>
</template>

<script lang="ts" setup>
    import { Card } from 'ant-design-vue';
    import { useRouter } from 'vue-router';
    import { FromPageType, RecordType } from '/@/enums/workflowEnum';
    import { ref, computed, onMounted, onBeforeMount, nextTick, defineAsyncComponent, reactive, defineComponent, watch} from 'vue';
     import { CheckCircleOutlined, StopOutlined, CloseOutlined, } from '@ant-design/icons-vue';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { useI18n } from '/@/hooks/web/useI18n';
    import { useMultipleTabStore } from '/@/store/modules/multipleTab';
    import useEventBus from '/@/hooks/event/useEventBus';
    import type { Rule } from 'ant-design-vue/es/form';
    import { getDictionary } from '/@/api/sales/Customer';
    import { useModal } from '/@/components/Modal';
    import { getLngPngAppro,approveLngPngAppro,getLngPngApproCompare,approveLngPngApproSZ,approveLngPngApproGD } from '/@/api/dayPlan/PngAppro';
    import dayjs from 'dayjs';
    import { getAppEnvConfig } from '/@/utils/env';
    import { message } from 'ant-design-vue';
    import { useUserStore } from '/@/store/modules/user';
    import basicForm from './basicForm.vue'

    const userStore = useUserStore();
    const userInfo = userStore.getUserInfo;

    const formType = ref('2'); // 0 新建 1 修改 2 查看
    const formRef = ref();
    const props = defineProps({
      disabled: false,
      id: ''
    
    });
    const { bus, FORM_LIST_MODIFIED } = useEventBus();

    const router = useRouter();
    const { currentRoute } = router;
    const isDisable = ref(false);
    const { formPath } = currentRoute.value.query;
    const pathArr = [];

    const tabStore = useMultipleTabStore();
    const formProps = ref(null);
    const formId = ref(currentRoute.value?.params?.id);
    const pageType = ref(currentRoute.value.query?.type);
    const pageId = ref(currentRoute.value.query?.id)
    
    const contractQty = ref()
    const spinning = ref(false);
    const curIdx = ref(null)
    const { notification } = useMessage();
    const { t } = useI18n();
    const hasDel = ref(false)
    const formState = reactive({

    });
     const formStateNew = reactive({

    });
    const [register, { openModal:openModal}] = useModal();
    const rules= reactive({
      // kNo: [{ required: true, message: "该项为必填项", trigger: 'change' }],
    });
    const layout = {
      labelCol: { span: 9 },
      wrapperCol: { span: 18 },
    }
    const title = ref('日计划审批')
    const titleNew = ref('')
    const dataList = ref([])
    const dataListNew = ref([])
    const basicFormRef = ref()
    let optionSelect= reactive({
      approCodeList: [],
    });
    onMounted(() => {
      getOption()
      if (pageId.value) {
        if (currentRoute.value.query.type=='compare') {
          getCompareInfo(pageId.value)
          return
        }
        getInfo(pageId.value)
      }
   
    });
    async function getCompareInfo(id) {
       spinning.value = true
      try {
      let data = await getLngPngApproCompare(id) || []
      spinning.value = false
      if (data.length == 1) {
        let obj = changeData(data[0])
        Object.assign(formState, {...obj.params})
        Object.assign(dataList.value, obj.list || [{}])
        title.value = '版本V'+ formState.verNo
      }
       if (data.length > 1) {
        let obj = changeData(data[0])
        Object.assign(formState, {...obj.params})
        Object.assign(dataList.value, obj.list || [{}])
        title.value = '版本V'+ formState.verNo

        let obj1 = changeData(data[1])
        Object.assign(formStateNew, {...obj1.params})
        Object.assign(dataListNew.value, obj1.list || [{}])
        titleNew.value = '版本V'+ formStateNew.verNo
      }

      } catch (error) {
        spinning.value = false
      }

    }
    async function getInfo(id)  {
      spinning.value = true
      try {
      let data = await getLngPngAppro(id)
      spinning.value = false
      let obj = changeData(data)
      Object.assign(formState, {...obj.params})
      Object.assign(dataList.value, obj.list || [{}])
      } catch (error) {
        spinning.value = false
      }
    }
    const changeData = (obj) => {
      let arr = obj.lngPngApproPurList || [{}]
      // const startDate = dayjs(obj.datePlan);
      // const endDate = dayjs(new Date());
      // const diffInDays = endDate.diff(startDate, 'day');
      // if (diffInDays == 0) {
      //   obj.dayDesc = '当日'
      // } else if (diffInDays == 1) {
      //   obj.dayDesc = '次日'
      // } else if (diffInDays > 1) {
      //   obj.dayDesc = diffInDays + '日后'
      // } else {
      //   obj.dayDesc = ''
      // }
      obj.qtyContractM3 = Number(obj.qtyContractM3)/10000
      obj.qtyPlanM3 = Number(obj.qtyPlanM3)/10000
      obj.qtyDemandM3 = Number(obj.qtyDemandM3)/10000
      obj.qtySalesM3 = Number(obj.qtySalesM3)/10000
      let num = 0;
      let num1 = 0;
      arr.forEach(v => {
        v.qtyDemandM3 = Number(v.qtyDemandM3)/10000
        v.qtySalesM3 = Number(v.qtySalesM3)/10000
        num+=(Number(v.qtySalesGj) || 0)
        num1+=(Number(v.qtySalesM3) || 0)
      });
      obj.qtySalesGj = num
      obj.qtySalesM3 = num1
      return {
        list : arr,
        params: obj
      }
    } 
    async function getOption() {
      optionSelect.approCodeList = await getDictionary('LNG_APPRO')

    }
    function close() {
      tabStore.closeTab(currentRoute.value, router);
    }
    async function checkBtn(type) {
      let data = basicFormRef.value.getFormValue()
      let arr = JSON.parse(JSON.stringify(data.list))
      arr.forEach(v=> {
        v.qtyDemandM3 = Number(v.qtyDemandM3)*10000
        v.qtySalesM3 = Number(v.qtySalesM3)*10000
      })
      let obj = {
        ...data.formInfo,
        qtyContractM3: Number(data.formInfo.qtyContractM3)*10000,
        qtyPlanM3: Number(data.formInfo.qtyPlanM3)*10000,
        qtyDemandM3: Number(data.formInfo.qtyDemandM3)*10000,
        qtySalesM3: Number(data.formInfo.qtySalesM3)*10000,
        lngPngApproPurList:arr
      }
      let params = {
        result: type == 'agree' ? 'C' : 'R',
        remark: formState.reply,
        data: [obj]
      }
      spinning.value = true;
      try {
        if (type == 'reject') {
          if (!formState.reply) {
            message.warn('请输入批复意见')
            return
          }
        }
        let request = ''
        if (formPath.includes('dayPlan/PngAppro/index')) {
          request = approveLngPngAppro
        }
        if (formPath.includes('dayPlan/pngPipeAppro/index')) {
          request = approveLngPngApproGD
        }
        if (formPath.includes('dayPlan/pngReceiveStationAppro/index')) {
          request = approveLngPngApproSZ
        }
        await request(params);
        spinning.value = false;
        notification.success({
          message: 'Tip',
          description: type == 'agree' ? '审批通过':'已驳回'
        }); //提示消息
        setTimeout(() => {
          bus.emit(FORM_LIST_MODIFIED, {});
          close();
        }, 500);
      }catch (errorInfo) {
        spinning.value = false;
      }
    }

</script>

<style lang="less" scoped>
    .page-bg-wrap {
        background-color: #fff;
    }

    .top-toolbar {
        min-height: 44px;
        margin-bottom: 12px;
        border-bottom: 1px solid #eee;
    }
    .pdcss {
      padding:0px 12px 6px 12px !important;
    }
    .dot {
      margin-right: 10px;
      display: flex;
      align-items: center;
      i{
        padding: 5px;
        font-style: normal;
      }
      span{
        width: 10px !important;
        height: 10px !important;
        border-radius: 50%;
        background: red;
        display: block;
      }
    }
    
</style>
