<template>
  <div class="common-dialog">
    <div class="common-dialog-content">
      <div class="common-dialog-title-box">
        <i class="common-dialog-title-icon" />
        <div>{{ props.id ? '修改物资申报' : '新增物资申报' }}</div>
      </div>
      <div class="common-dialog-box">
        <div class="text-box">
          <div class="text1">申报金额：</div>
          <div v-show="!!detailData.declaration_amount" class="text2">{{ formatToTwoDecimalPlaces(detailData.declaration_amount) }}元</div>
        </div>
        <el-form ref="formRef" :model="detailData" style="width: 100%">
          <el-table :data="detailData.detail" border :height="height">
            <el-table-column label="序号" width="80" align="center">
              <template #default="{ $index }">
                <span>{{ $index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="物资名称" prop="material_name" align="center">
              <template #default="scope">
                <el-form-item :prop="'detail.' + scope.$index + '.material_type'" :rules="rules.material_name">
                  <el-input v-model="scope.row.material_name" readonly>
                    <template #append>
                      <el-button @click="handleShowSelect(scope.$index)">选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="仓库" prop="warehouse_id" align="center" />
            <el-table-column label="物资类型" prop="material_type" align="center" />
            <el-table-column label="物资数量（件）" prop="material_quantity" align="center">
              <template #default="scope">
                <el-form-item :prop="`detail.${scope.$index}.material_quantity`" :rules="rules.material_quantity">
                  <el-input v-model="scope.row.material_quantity" type="number" placeholder="请输入" @input="calcTotalAmount" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="物资单价（元）" prop="material_unit_price" align="center">
              <template #default="scope">
                <el-form-item :prop="'detail.' + scope.$index + '.material_unit_price'" :rules="rules.material_unit_price">
                  <el-input v-model="scope.row.material_unit_price" type="number" placeholder="请输入" @input="calcTotalAmount" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="物资用途" prop="material_purpose" align="center">
              <template #default="scope">
                <el-form-item :prop="'detail.' + scope.$index + '.material_purpose'" :rules="rules.material_purpose">
                  <el-input v-model="scope.row.material_purpose" type="textarea" autosize placeholder="请输入" />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <div class="common-dialog-footer" style="margin-top: 18px">
          <el-row :span="24" :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button @click="handleReturn">取消</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="primary" @click="handleAddRow">新增一项</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button :loading="buttonLoading" type="primary" @click="submitForm(formRef)">确定</el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <materialTreeSelect v-model="showSelect" @confirm="handleSelectChange" />
  </div>
</template>

<script setup lang="ts">
import {
  createProcurement,
  getDeclarationDetail,
  updateProcurement
} from '@/api/comprehensiveGuarantee/materialReserveManagement/materialsDeclaration';
import BigNumber from 'bignumber.js';
import materialTreeSelect from './materialTreeSelect'
import { formatToTwoDecimalPlaces, isNumericString } from '@/utils';
import { getMaterialWarehouseList } from '@/api/comprehensiveGuarantee/materialReserveManagement/godownManagement';

const props = defineProps({
  id: String
});

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emits = defineEmits(['close']);

const formRef = ref();
let detailData = reactive({
  declaration_amount: '',
  detail: []
});
const rules = reactive({
  material_name: [{ required: true, message: '请选择物资名称', trigger: 'change' }],
  material_quantity: [{ required: true, message: '请输入物资数量', trigger: 'blur' }],
  material_unit_price: [{ required: true, message: '请输入物资单价', trigger: 'blur' }],
  material_purpose: [{ required: true, message: '请输入物资用途', trigger: 'blur' }]
});
let buttonLoading = ref(false);
let warehouseList = ref([]);
let materialList = ref([]);

// 计算总额
const calcTotalAmount = () => {
  let total = new BigNumber('0');
  detailData.detail.forEach((item) => {
    if (isNumericString(item.material_quantity) && isNumericString(item.material_unit_price)) {
      const num = new BigNumber(item.material_quantity).times(new BigNumber(item.material_unit_price));
      total = total.plus(num);
    }
  });
  detailData.declaration_amount = total.toString();
};

const handleAddRow = () => {
  const newRow = {
    warehouse_id: '',
    material_name: '',
    material_type: '',
    material_code: '',
    material_quantity: '',
    material_unit_price: '',
    material_purpose: ''
  };
  detailData.detail.push(newRow);
};

const handleReturn = () => {
  emits('close');
};

const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      if (props.id) {
        updateProcurement(detailData, props.id).then(() => {
          proxy.$modal.msgSuccess('修改成功');
          emits('close', true);
        });
      } else {
        createProcurement(detailData).then(() => {
          proxy.$modal.msgSuccess('新增成功');
          emits('close', true);
        });
      }
    } else {
      nextTick(() => {
        let isError = document.getElementsByClassName('is-error');
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: 'center',
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: 'smooth'
        });
      });
      proxy.$modal.msgError('表单校验失败');
      return false;
    }
  });
};

let showSelect = ref(false);
let selectIndex = ref('');
const handleShowSelect = (index) => {
  selectIndex.value = index;
  showSelect.value = true;
};
const handleSelectChange = (data) => {
  detailData.detail[selectIndex.value].material_code = data.id;
  detailData.detail[selectIndex.value].material_name = data.label;
  detailData.detail[selectIndex.value].warehouse_id = data.warehouse_id;
  detailData.detail[selectIndex.value].material_type = data.type;
};

let height = ref(300);
// 计算表格高度
const calcHeight = () => {
  const el = document.getElementsByClassName('common-dialog-content')[0];
  height.value = el && el.clientHeight - 173 > 400 ? el.clientHeight - 173 : 300;
};
onMounted(() => {
  if (props.id) {
    getDeclarationDetail(props.id).then((res) => {
      detailData.declaration_amount = res.data.declaration_amount;
      detailData.detail = res.data.detail;
    });
  } else {
    handleAddRow();
  }
  getMaterialWarehouseList().then((res) => {
    warehouseList.value = res.data;
  });
  // getMaterialList().then((res) => {
  //   materialList.value = res.data;
  // });
  calcHeight();
  window.addEventListener('resize', calcHeight);
});
onUnmounted(() => {
  window.removeEventListener('resize', calcHeight);
});
</script>

<style lang="scss" scoped>
.text-box {
  width: 100%;
  display: flex;
  align-items: center;
  padding-bottom: 10px;
  color: rgba(0, 0, 0, 0.85);
  .text1 {
    font-size: 18px;
    font-weight: bold;
  }
  .text2 {
    font-size: 18px;
  }
}
.el-form-item {
  margin: 18px 0;
}
:deep(.custom-disabled) {
  .el-select__wrapper.is-disabled,
  .el-input__wrapper,
  .el-textarea__inner {
    background-color: #ffffff !important;
  }
  .el-select__wrapper.is-disabled .el-select__selected-item,
  .el-input__inner,
  .el-textarea__inner {
    color: rgba(0, 0, 0, 0.85) !important;
    -webkit-text-fill-color: rgba(0, 0, 0, 0.85) !important;
  }
}
</style>
