<template>
  <div style="width: 100%; padding: 0px 15px">
    <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
      <template #refundDetailList>
        <div style="width: 100%">
          <el-button type="primary" @click="clickAdd()">添加行</el-button>
          <el-table :data="formData.data.refundDetailList" style="width: 100%; margin-top: 16px">
            <el-table-column label="退货单号" width="220">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'refundDetailList.' + $index + '.salesReturnId'" :rules="rules.salesReturnId" :inline-message="true">
                    <el-select v-model="row.salesReturnId" placeholder="请选择退货单号" style="width: 100%" @change="changePurchaseId(row)">
                      <el-option v-for="item in returnGoods" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="approvedDate" label="退货时间" width="160" />
            <el-table-column label="退货状态" width="140">
              <template #default="{ row }">
                <div style="width: 100%">
                  {{ dictValueLabel(row.status, returnStatus) }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="退款金额" width="180">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'refundDetailList.' + $index + '.money'" :rules="rules.money" :inline-message="true">
                    <el-input-number
                      onmousewheel="return false;"
                      v-model="row.money"
                      placeholder="请输入金额"
                      style="width: 100%"
                      :precision="2"
                      :controls="false"
                      :min="0.01"
                      :disabled="row.id"
                      @change="changeMoney()" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="备注">
              <template #default="{ row, $index }">
                <div style="width: 100%">
                  <el-form-item :prop="'refundDetailList.' + $index + '.remark'" :rules="rules.remark" :inline-message="true">
                    <el-input v-model="row.remark" placeholder="请输入款项说明" style="width: 100%" />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="{ row, $index }">
                <el-button type="primary" link @click="handleRemove($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <br />
        </div>
      </template>
    </byForm>
  </div>
</template>

<script setup>
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";
import moment from "moment";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";

const route = useRoute();
const { proxy } = getCurrentInstance();
const supplierList = ref([]);
const returnGoods = ref([]);
const returnStatus = ref([
  {
    label: "审批中",
    value: 10,
  },
  {
    label: "驳回",
    value: 20,
  },
  {
    label: "待退货",
    value: 30,
  },
]);
let formData = reactive({
  data: {
    supplyId: "",
    deptName: useUserStore().user.dept.deptName,
    refundName: useUserStore().user.dept.userName,
    amount: "",
    remark: "",
    refundTime: moment().format("yyyy-MM-DD HH:mm:ss"),
    refundDetailList: [],
  },
});
const submit = ref(null);
const judgeStatus = () => {
  if (props.queryData.recordList && props.queryData.recordList.length > 0) {
    let data = props.queryData.recordList.filter((item) => item.status === 2 && item.nodeType !== 1);
    if (data && data.length > 0) {
      return true;
    }
  }
  return false;
};
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
  disabled: false,
});
const formConfig = computed(() => {
  return [
    {
      type: "title",
      title: "基础信息",
      label: "",
    },
    {
      type: "input",
      prop: "deptName",
      label: "申请部门",
      required: true,
      itemType: "text",
      disabled: true,
      itemWidth: 25,
    },
    {
      type: "input",
      prop: "refundName",
      label: "申请人",
      required: true,
      itemType: "text",
      disabled: true,
      itemWidth: 25,
    },
    {
      type: "input",
      prop: "refundTime",
      label: "申请时间",
      required: true,
      itemType: "text",
      disabled: true,
      itemWidth: 25,
    },
    {
      type: "select",
      label: "供应商",
      prop: "supplyId",
      data: supplierList.value,
      fn: (val) => {
        changeSupply(val);
      },
    },
    {
      type: "input",
      prop: "remark",
      label: "退款原因",
      itemType: "textarea",
    },
    {
      type: "slot",
      prop: "refundDetailList",
      slotName: "refundDetailList",
      label: "关联退货",
    },
    {
      type: "input",
      prop: "amount",
      label: "应退款金额",
      required: true,
      itemType: "text",
      disabled: true,
    },
  ];
});
let rules = ref({
  supplyId: [{ required: true, message: "请选择供应商", trigger: "change" }],
  salesReturnId: [{ required: true, message: "请选择退货单号", trigger: "change" }],
  money: [{ required: true, message: "请输入退款金额", trigger: "blur" }],
});
const getDict = () => {
  proxy.post("/supplierInfo/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      supplierList.value = res.rows.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
    }
  });
};
getDict();
const changeSupply = (val) => {
  if (val) {
    proxy.get("/salesReturn/getBySupplyId", { supplyId: val }).then((res) => {
      if (res.data && res.data.length > 0) {
        returnGoods.value = res.data.map((item) => {
          return {
            ...item,
            value: item.id,
            label: item.code,
          };
        });
      } else {
        returnGoods.value = [];
      }
    });
  } else {
    returnGoods.value = [];
  }
};
const clickAdd = () => {
  if (formData.data.refundDetailList && formData.data.refundDetailList.length > 0) {
    formData.data.refundDetailList.push({ salesReturnId: "", money: undefined, remark: "", approvedDate: "", status: "" });
  } else {
    formData.data.refundDetailList = [{ salesReturnId: "", money: undefined, remark: "", approvedDate: "", status: "" }];
  }
};
const handleRemove = (index) => {
  formData.data.refundDetailList.splice(index, 1);
};
const changeMoney = () => {
  let money = 0;
  for (let i = 0; i < formData.data.refundDetailList.length; i++) {
    if (formData.data.refundDetailList[i].money) {
      money = parseFloat(Number(money) + Number(formData.data.refundDetailList[i].money)).toFixed(2);
    }
  }
  formData.data.amount = money;
};
const handleSubmit = async () => {
  let status = await submit.value.handleSubmit(() => {});
  if (status) {
    if (formData.data.refundDetailList && formData.data.refundDetailList.length > 0) {
      return true;
    } else {
      ElMessage("请添加至少一条退货信息");
    }
    return false;
  }
  return status;
};
const getFormData = () => {
  return formData.data;
};
// 向父组件暴露
defineExpose({
  getFormData,
  handleSubmit,
});
// 接收父组件的传值
const props = defineProps({
  queryData: Object,
});
watch(
  props.queryData,
  () => {
    formOption.disabled = judgeStatus();
    if (props.queryData && (route.query.processType == 10 || route.query.processType == 20)) {
      for (var text in props.queryData) {
        formData.data[text] = props.queryData[text];
      }
    }
  },
  {
    deep: true,
  }
);
// 获取用户信息并赋默认值
const userInfo = useUserStore().user;
onMounted(() => {
  formData.data.refundName = userInfo.nickName;
});
const changePurchaseId = (row) => {
  if (row.salesReturnId) {
    let data = returnGoods.value.filter((item) => item.id === row.salesReturnId);
    if (data && data.length > 0) {
      row.approvedDate = data[0].approvedDate;
      row.status = data[0].status;
    } else {
      row.approvedDate = "";
      row.status = "";
    }
  } else {
    row.approvedDate = "";
    row.status = "";
  }
};
</script>

<style lang="scss" scoped>
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
