<!-- 
  TODO 新增临时收货
 -->
<template>
  <SysDialog
    class="tmp-receiver-add"
    :visible="dialog.visible"
    :confirm-loading="dialog.confirmLoading"
    v-bind="getBindValue"
    :title="dialog.title"
    @onClose="onclose"
    @onConfirm="confirm"
  >
    <template #content>
      <el-form
        ref="addTmpReceiverRef"
        :model="addTmpReceiverForm"
        inline
        :rules="addTmpReceiverFormRules"
        label-width="80px"
      >
        <!-- 移动端版本 -->
        <el-row v-show="getIsPhone" style="padding-top: 12px">
          <el-col :span="24">
            <el-form-item
              prop="customerId"
              label="客户名称"
              :style="setFormItemWidth"
            >
              <BaseSelect
                v-model:modelValue="addTmpReceiverForm.customerId"
                :clearable="true"
                :options="customertList"
                placeholder="请选择客户"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              prop="currencyCode"
              label="币种"
              :style="setFormItemWidth"
            >
              <BaseSelect
                v-model:modelValue="addTmpReceiverForm.currencyCode"
                :clearable="true"
                :options="currencyList"
                placeholder="请选择币种"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              prop="beginDate"
              label="起始时间"
              :style="setFormItemWidth"
            >
              <el-date-picker
                v-model="addTmpReceiverForm.beginDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="起始时间"
                :defaultTime="defaultTime"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              prop="endDate"
              label="结束时间"
              :style="setFormItemWidth"
            >
              <el-date-picker
                v-model="addTmpReceiverForm.endDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="结束时间"
                :defaultTime="defaultTime"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="额度"
              :style="setFormItemWidth"
              :rules="receiveRules.tempLimit"
            >
              <el-input
                type="number"
                v-model="addTmpReceiverForm.tempLimit"
                v-clear-only-regex="/^\+?(\d+(\.\d*)?|\.\d+)$/"
                @focus="onTempLimitFocus"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="凭证" :rules="receiveRules.files">
              <el-alert title="温馨提示：图片上传最大尺寸1MB" type="warning" :closable="false" />
              <div style="width: 90px;">
                <el-upload
                  ref="uploadRef"
                  class="voucher-uploader"
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="handleOnChangeUpload"
                >
                  <img
                    v-if="isArrayLength(receiveState.imageUploadUrlList)"
                    :src="receiveState.imageUploadUrlList[0]"
                    class="upload-url"
                  />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  <span v-show="isArrayLength(receiveState.imageUploadUrlList)" class="upload-add">
                    <el-icon><Upload /></el-icon>
                  </span>
                </el-upload>
                <span
                  v-show="isArrayLength(receiveState.imageUploadUrlList)"
                  class="upload-preview"
                  @click="handlePictureCardPreview(1)"
                >
                  <el-icon><zoom-in /></el-icon>
                </span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-show="!getIsPhone">
          <el-col :span="12">
            <el-form-item
              prop="customerId"
              label="客户名称"
              :style="setFormItemWidth"
            >
              <BaseSelect
                v-model:modelValue="addTmpReceiverForm.customerId"
                :clearable="true"
                :options="customertList"
                placeholder="请选择客户"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="currencyCode"
              label="币种"
              :style="setFormItemWidth"
            >
              <BaseSelect
                v-model:modelValue="addTmpReceiverForm.currencyCode"
                :clearable="true"
                :options="currencyList"
                placeholder="请选择币种"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item
              prop="beginDate"
              label="时间范围"
              :style="setFormItemWidth"
            >
              <el-date-picker
                v-model="dateArr"
                type="daterange"
                start-placeholder="起始时间"
                end-placeholder="结束时间"
                @change="changeDate"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item
              prop="beginDate"
              label="起始时间"
              :style="setFormItemWidth"
            >
              <el-date-picker
                v-model="addTmpReceiverForm.beginDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="起始时间"
                :defaultTime="defaultTime"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="endDate"
              label="结束时间"
              :style="setFormItemWidth"
            >
              <el-date-picker
                v-model="addTmpReceiverForm.endDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="结束时间"
                :defaultTime="defaultTime"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="额度"
              prop="tempLimit"
              :style="setFormItemWidth"
              :rules="receiveRules.tempLimit"
            >
              <el-input
                type="number"
                v-clear-only-regex="/^\+?(\d+(\.\d*)?|\.\d+)$/"
                v-model="addTmpReceiverForm.tempLimit"
                @focus="onTempLimitFocus"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="凭证"
              prop="files"
              :rules="receiveRules.files"
              :style="setFormItemWidth"
            >
              <el-upload
                ref="uploadRef"
                class="voucher-uploader"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleOnChangeUpload"
              >
                <el-button style="width: 100%">
                  上传<el-icon class="el-icon--right"><Upload /></el-icon>
                </el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="info-tips">
              <el-alert title="温馨提示：图片上传最大尺寸1MB" type="warning" :closable="false" />
            </div>
            <div class="img-view-warp" v-if="receiveState.imageUploadUrlList.length > 0">
              <div class="img-item" v-for="(url, index) in receiveState.imageUploadUrlList" :key="index">
                <img
                  :src="url"
                  class="view-img"
                />
                <div class="btns-warp">
                  <span
                    v-show="url"
                    class="btn-preview"
                    @click="handlePictureCardPreview(index)"
                  >
                    <el-icon><zoom-in /></el-icon>
                  </span>
                  <span 
                    v-show="url" 
                    class="btn-delete"
                    @click="handlePictureCardDelete(index, url)"
                  >
                    <el-icon><Delete /></el-icon>
                  </span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 凭证照片 -->
      <el-image
        class="define-image-preview"
        ref="imagePreviewRef"
        :src="receiveState.imageUploadUrlList[0]"
        :preview-src-list="receiveState.imageUploadUrlList"
        :initial-index="viewIndex"
        :hide-on-click-modal="true"
        fit="cover"
      >
      </el-image>
    </template>
  </SysDialog>
</template>
<script lang="ts" setup>
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import { useEleFormValidate } from "@/hooks/useEleFormValidate";
import type { ListIitem } from "@/api/base/BaseDataModel";
import BaseSelect from "@/components/QuerySelect/BaseSelect.vue";
import { ref, reactive, unref, computed, nextTick } from "vue";
import { TmpReceiverType } from "@/type/BaseEnum";
import { TmpReceiveDtoAdd } from "@/api/accountPeriod/accountPeriodModel";
// import { formatDateTime } from "@/utils/dateFormate";
import { menuStore } from "@/store/menu";
import { deal_FindGetItemName } from "@/utils/dealFindData";
import { ElMessage, UploadInstance, UploadProps } from "element-plus";
// import { isArray } from "@/utils/is";
import { Department } from "@/type/BaseBusinessFeeseType";
import { userStore } from "@/store/user";
import { cloneDeep } from "@/utils/cloneDeep";
import { isArrayLength, isStrings } from "@/utils/is";
import { getStartDayAndNextDay } from "@/utils/dateTimeStr";

//弹框属性
const { dialog, onClose, onShow, setLoading } = useDialog();
// 弹框一些配置
const getBindValue = reactive({
  title: "新增临时收货",
  width: "720",
  height: 0,
});
const props = defineProps<{
  customertList: ListIitem[];
  currencyList: ListIitem[];
}>();
const emit = defineEmits(["saveTmpReceiver"]);
const menustore = menuStore();
const getIsPhone = computed(() => menustore.getIsPhone);
// 校验表单
const { formValidate, resetForm } = useEleFormValidate();

// 校验
const addTmpReceiverFormRules = reactive({
  customerId: [{ required: true, message: "请选择客户", trigger: "change" }],
  currencyCode: [{ required: true, message: "请选择币种", trigger: "change" }],
  beginDate: [{ required: true, message: "请选择起始时间", trigger: "change" }],
  endDate: [{ required: true, message: "请选择结束时间", trigger: "change" }],
});
// 表单数据
const addTmpReceiverForm = reactive<Partial<TmpReceiveDtoAdd>>({
  id: undefined,
  customerId: undefined,
  currencyCode: "CNY",
  customerName: undefined,
  beginDate: undefined,
  endDate: undefined,
  tempLimit: undefined,
  files: [],
  type: undefined,
});
// 查看照片索引
const viewIndex = ref(0)
const dateArr = ref([]);
// const userstore = userStore();
// const getSysUserRoleDto = computed(() => userstore.sysUserRoleDto);
const receiveRules = reactive({
  tempLimit: [{ required: true, message: "请输入额度", trigger: "blur" }],
  isTempLimit: [{ required: false, message: "请输入额度", trigger: "blur" }],
  files: [{ required: true, message: "请选择上传文件", trigger: "change" }],
  isFile: [{ required: false, message: "请选择上传文件", trigger: "change" }],
});
// 是否校验额度
// const getTempLimitRules = computed(() => {
//   if (unref(getSysUserRoleDto).roleId === Department.SELL)
//     return receiveRules.tempLimit;
//   return receiveRules.isTempLimit;
// });
// // 是否校验上传文件
// const getFileRules = computed(() => {
//   if (unref(getSysUserRoleDto).roleId === Department.SELL)
//     return receiveRules.files;
//   return receiveRules.isFile;
// });
// const changeDate = (date: Date[]) => {
//   if (isArray(date)) {
//     addTmpReceiverForm.beginDate = formatDateTime(date[0]);
//     addTmpReceiverForm.endDate = formatDateTime(date[1]);
//   } else {
//     addTmpReceiverForm.beginDate = undefined;
//     addTmpReceiverForm.endDate = undefined;
//   }
// };
// ref dom
const addTmpReceiverRef = ref();
// col宽度百分比
const setFormItemWidth = computed(() => {
  return { width: `calc(100% - 32px)` };
});
// 初始化时间格式
const defaultTime = new Date(2000, 1, 1, 6, 0, 0);
// 上传凭证
const receiveState = reactive({
  imageUploadUrlList: [] as string[], //照片url list
});
const uploadRef = ref<UploadInstance>();
const imagePreviewRef = ref();
// 额度选中
const onTempLimitFocus = (e) => {
  e.target && e.target.select();
};
// 今天时间与明天时间
const [currentFormattedDate, endFormattedDate] = getStartDayAndNextDay()
// 上传照片
const handleOnChangeUpload: UploadProps["onChange"] = (uploadFile) => {
  if (!uploadFile.raw) return;
  if (uploadFile.raw.size / 1024 / 1024 > 1) {
    ElMessage.warning("图片上传最大尺寸为1MB！");
    return;
  }
  if (!uploadFile.raw.type.includes("image/")) {
    ElMessage.error("目前只支持上传照片！");
    return false;
  }
  // console.log(uploadFile, ":uploadFile");
  // if (addTmpReceiverForm.type === TmpReceiverType.EDIT) {
  //   receiveState.imageUploadUrlList = []
  // }
  if (uploadFile.raw) {
    const imageUrl = URL.createObjectURL(uploadFile.raw);
    receiveState.imageUploadUrlList.push(imageUrl)
    addTmpReceiverForm.files?.push(uploadFile.raw)
  }
  unref(uploadRef)?.clearFiles();
};
// 查看凭证照片
const handlePictureCardPreview = (index: number) => {
  viewIndex.value = index
  nextTick(() => {
    const imagePreviewDom = unref(imagePreviewRef);
    if (imagePreviewDom && imagePreviewDom.$el) {
      const targetDiv = imagePreviewDom.$el.querySelector(".el-image__preview");
      if (targetDiv) {
        // @ts-ignore
        targetDiv.click();
      }
    }
  })
};
// 删除凭证照片
const handlePictureCardDelete = (index: number, url: string) => {
  const findIndex = receiveState.imageUploadUrlList.findIndex(item => item === url)
  receiveState.imageUploadUrlList.splice(index, 1)
  if (addTmpReceiverForm.type === TmpReceiverType.EDIT) {
    url.includes('blob:') && addTmpReceiverForm.files && addTmpReceiverForm.files.splice(findIndex, 1)
  } else {
    addTmpReceiverForm.files && addTmpReceiverForm.files.splice(index, 1)
  }
}

// 隐藏
const onclose = () => {
  // 清空数据
  resetForm(addTmpReceiverRef.value);
  Object.keys(addTmpReceiverForm).forEach((key) => {
    addTmpReceiverForm[key] = undefined;
  });
  dateArr.value = [];
  receiveState.imageUploadUrlList = [];
  addTmpReceiverForm.files = []
  addTmpReceiverForm.currencyCode = 'CNY'
  onClose();
};
// 显示
const show = (type: number, data: Recordable) => {
  addTmpReceiverForm.beginDate = currentFormattedDate
  addTmpReceiverForm.endDate = endFormattedDate
  // 添加、编辑类型
  addTmpReceiverForm.type = type;
  getBindValue.width = unref(getIsPhone) ? "100%" : "720";
  // 标题
  type === TmpReceiverType.ADD
    ? (dialog.title = "新增临时收货")
    : (dialog.title = "编辑临时收货");
  onShow();
  nextTick(() => {
    if (type === TmpReceiverType.EDIT) {
      // 编辑
      Object.keys(addTmpReceiverForm).forEach((key) => {
        addTmpReceiverForm[key] = data[key];
      });
      addTmpReceiverForm.type = type;
      addTmpReceiverForm.customerId = String(addTmpReceiverForm.customerId);
      addTmpReceiverForm.files = []
      receiveState.imageUploadUrlList = data.uploadFileList || []
    }
  });
};

// 确定
const confirm = async () => {
  const isValidate = await formValidate(addTmpReceiverRef.value);
  if (!isValidate) return;
  addTmpReceiverForm.customerName = deal_FindGetItemName(
    addTmpReceiverForm.customerId,
    props.customertList
  );
  addTmpReceiverForm.tempLimit = Number(addTmpReceiverForm.tempLimit);
  // if (unref(getIsPhone)) {
  //   addTmpReceiverForm.beginDate = formatDateTime(addTmpReceiverForm.beginDate);
  //   addTmpReceiverForm.endDate = formatDateTime(addTmpReceiverForm.endDate);
  // }
  const params = cloneDeep(addTmpReceiverForm) as TmpReceiveDtoAdd;
  delete params.files;
  // console.log(addTmpReceiverForm, ":addTmpReceiverForm");
  setLoading(true);
  emit("saveTmpReceiver", params, addTmpReceiverForm.files, setLoading, onclose);
};

//父组件调用子组件显示弹框
//暴露出去给外部使用
defineExpose({
  show,
});
</script>
<style lang="scss" scoped>
.tmp-receiver-add .voucher-uploader {
  flex: 1;
}
.tmp-receiver-add .voucher-uploader :deep(.el-upload) {
  width: 100%;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: 0.2s;
}
.tmp-receiver-add .voucher-uploader :deep(.el-upload):hover {
  border-color: #409eff;
}
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  text-align: center;
}
.tmp-receiver-add .upload-url {
  width: 90px;
  height: 90px;
}
.tmp-receiver-add .upload-preview {
  position: absolute;
  top: 50%;
  left: 25%;
  transform: translate(-25%, -50%);
  font-size: 24px;
  color: #064bd0;
  cursor: pointer;
}
.tmp-receiver-add .upload-add {
  position: absolute;
  top: 50%;
  left: 80%;
  transform: translate(-80%, -40%);
  font-size: 24px;
  color: #064bd0;
  cursor: pointer;
}
.tmp-receiver-add .define-image-preview {
  position: absolute;
  top: -9999px;
  left: -9999px;
}
.tmp-receiver-add {
  .info-tips {
    margin-left: 80px;
    margin-right: 32px;
    margin-bottom: 10px;
  }
  .img-view-warp {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    margin-left: 80px;
    padding-bottom: 12px;
    .img-item {
      position: relative;
      width: 90px;
      height: 90px;
      margin-right: 10px;
      &:nth-child(6) ~ div {
        margin-top: 10px;
      }
      .view-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 6px;
      }
      .btns-warp {
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        width: 100%;
        height: 100%;
        border-radius: 6px;
        background-color: #00000080;
        transition: opacity .3s;
        .btn-preview {
          position: absolute;
          top: 50%;
          left: 25%;
          transform: translate(-25%, -50%);
          font-size: 23px;
          color: #ffffff;
          cursor: pointer;
        }
        .btn-delete {
          position: absolute;
          top: 50%;
          left: 80%;
          transform: translate(-80%, -50%);
          font-size: 23px;
          color: red;
          cursor: pointer;
        }
      }
      :hover {
        opacity: 1;
      }
    }
  }
}
</style>
