<template>
  <el-dialog custom-class="custom-dialog" class="border" width="500px" :title="title"
             v-model="visible">
    <!--显示转签弹出框-->
    <div v-if="type === 3" style="margin-bottom: 10px;">
      <span>转交给谁：</span>
      <el-button size="mini" icon="User" @click="chooseUser">选择人员</el-button>
      <div class="userStyle" v-for="(user, i) in userList" :key="i">
        <span @click="delDept(i)">×</span>
        <el-avatar :src="user.avatar"/>
        <el-tooltip class="item" effect="dark" :content="user.name" placement="bottom-start">
          <span>{{ user.name }}</span>
        </el-tooltip>
      </div>
    </div>
    <!--显示退回节点弹出框-->
    <div v-if="type === 4" style="margin-bottom: 10px">
      <span>回退节点：</span>
      <el-select v-if="userTaskOption.length >0 " v-model="rollBackId" slot="prepend" placeholder="选择要回退到的节点" filterable clearable>
        <el-option v-for="(option,index) in userTaskOption" :key="index"
                   :label="option.label" :value="option.value"/>
      </el-select>
      <span v-if="userTaskOption.length <=0 " style="margin-left: 10px;color: rgb(140, 140, 140);">暂无可回退节点</span>
    </div>
    <!--显示增加审批人弹出框-->
    <div v-if="type === 5" style="margin-bottom: 10px;">
      <span>给谁加签：</span>
      <el-button size="mini" icon="User" @click="chooseUser">选择人员</el-button>
      <div class="userStyle" v-for="(user, i) in userList" :key="i">
        <span @click="delDept(i)">×</span>
        <el-avatar :src="user.avatar"/>
        <el-tooltip class="item" effect="dark" :content="user.name" placement="bottom-start">
          <span>{{ user.name }}</span>
        </el-tooltip>
      </div>
    </div>
    <div class="el-textarea">
      <el-input
          type="textarea"
          :rows="4"
          maxlength="255"
          show-word-limit
          placeholder="评论内容"
          v-model="context">
      </el-input>
    </div>
    <div style="margin: 20px 0;" v-if="imageList && imageList.length > 0">
      <el-upload :file-list="imageList"
                 :limit="imageSize" with-credentials
                 :multiple="imageSize > 0"
                 :data="uploadParams"
                 list-type="picture-card"
                 :action="uploadFileUrl"
                 :headers="headers"
                 :auto-upload="true"
                 :on-success="handleUploadSuccess"
                 :before-upload="beforeUpload">
        <el-icon>
          <Plus />
        </el-icon>
<!--        <i slot="default" class="el-icon-plus"></i>-->
        <div slot="file" slot-scope="{file}">
          <img style="width: 100%;height: 100%" :src="file.url" alt="">
          <label class="el-upload-list__item-status-label">
            <i class="el-icon-upload-success el-icon-check"></i>
          </label>
          <span class="el-upload-list__item-actions">
             <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                <i class="el-icon-zoom-in"></i>
              </span>
              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
                <i class="el-icon-download"></i>
              </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                <i class="el-icon-delete"></i>
              </span>
          </span>
        </div>
        <div slot="tip">添加图片 {{ sizeTip }}</div>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" center append-to-body>
        <div>
          <img width="100%" :src="dialogImageUrl" alt="" style="z-index: 3435">
        </div>
      </el-dialog>
    </div>
    <el-upload style="margin-top: 10px" :file-list="attachmentList"
               :limit="attachmentMaxSize" with-credentials
               :multiple="attachmentMaxSize > 0"
               :action="uploadFileUrl"
               :headers="headers"
               :auto-upload="true"
               :on-success="handleAttachmentUploadSuccess"
               :before-upload="beforeAttachmentUpload"
               :on-remove="handleRemoveAttachment"
    >
      <el-button size="small" round >
        <el-icon>
          <Plus />
        </el-icon>
        <span>选择文件</span>
      </el-button>
      <div slot="tip" style="margin-left: 5px"> 添加附件 {{ attachmentTip }}</div>
    </el-upload>

    <div slot="footer">
      <el-button size="mini" @click="visible = false; emit('cancel')">取 消</el-button>
      <el-button size="mini" type="primary" @click="selectConfirm">确 定</el-button>
    </div>
    <user-picker :multiple="false" ref="userPicker" title="请选择人员" v-model:value="userList" @ok="selected"/>

  </el-dialog>
</template>

<script setup>
import {deleteFile} from '@/api/workflow/process-file.js'
const baseURL = import.meta.env.VITE_BASE_URL
import {computed, defineProps,defineEmits} from "vue";
import {useProcessStore} from '@/stores/processStore.js'
import { getToken } from '@/utils/auth'
import {ElMessage} from "element-plus";
import UserPicker from "../process/common/UserPicker.vue";
const processStore = useProcessStore()
const emit = defineEmits()

const props = defineProps({
  title: {
    type: String,
    default: "添加评论"
  },
  placeholder: {
    type: String,
    default: "评论内容"
  },
  imageSize: {
    type: Number,
    default: 5
  },
  type: {
    type: Number,
    default: 1
  },
  attachmentMaxSize: {
    type: Number,
    default: 100
  }
});

const sizeTip = computed(() => {
  return props.imageSize > 0 ? `| 每张图不超过${props.imageSize}MB` : "";
});

const attachmentTip = computed(() => {
  return props.attachmentMaxSize > 0 ? `| 单个附件不超过${props.attachmentMaxSize}MB` : "";
});

const userTaskOption = computed(() => {
  let optionList = processStore.userTaskOption.value;
  if (optionList) {
    return optionList;
  } else {
    return [];
  }
});
const userList = ref([])
const userPicker = ref()
const visible = ref(false);
const disabled = ref(false);
const imageList = ref([]);
const attachmentList = ref([]);
const uploadParams = ref({});
const uploadFileUrl = ref(baseURL + "/workflow/process/file");
const headers = ref({
  authorization: getToken()
});
const context = ref(null);
const rollBackId = ref(null);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const chooseUser=()=>{
  userPicker.value.showUserPicker()
}
const show = () => {
  visible.value = true;
};

const handleChange = (file, imageList) => {
  imageList.value = imageList.slice(-3);
};

const handleUploadSuccess = (res, file) => {
  if (res.code !== 1000) {
    ElMessage.error("上传失败");
  }
  let data = res.data;
  imageList.value.push(data);
};

const handleAttachmentUploadSuccess = (res, file) => {
  if (res.code !== 1000) {
    ElMessage.error("上传失败");
  }
  let data = res.data;
  attachmentList.value.push(data);
};

const beforeAttachmentUpload = (file) => {
  if (props.attachmentMaxSize > 0 && file.size / 1024 / 1024 > props.attachmentMaxSize) {
    ElMessage.warning(`单张图片最大不超过 ${props.attachmentMaxSize}MB`);
    return false;
  } else {
    return true;
  }
};

const beforeUpload = (file) => {
  const alows = ["image/jpeg", "image/png", "image/gif", "image/jpg"];
  if (alows.indexOf(file.type) === -1) {
    ElMessage.warning("存在不支持的图片格式");
  } else if (props.imageSize > 0 && file.size / 1024 / 1024 > props.imageSize) {
    ElMessage.warning(`单张图片最大不超过 ${props.imageSize}MB`);
  } else {
    return true;
  }
  return false;
};

const handlePictureCardPreview = (file) => {
  dialogVisible.value = true;
  dialogImageUrl.value = file.url;
};

const handleDownload = (file) => {
  console.log(file);
};
const handleRemoveAttachment=(file)=>{
  handleRemove(file.response.data)
}
const handleRemove = (file) => {
  deleteFile(file.id).then(res => {
    if (res.code === 1000) {
      ElMessage.success("删除成功");
      this.fileList.splice(this.fileList.findIndex((item) => item.id === file.id), 1);
    }
  });
};

const selectConfirm = () => {
  let fileList = [];
  attachmentList.value.forEach((attachment) => {
    fileList.push({
      id: attachment.id,
      name: attachment.name,
      isImage: attachment.isImage,
      size: attachment.size,
      url: attachment.url
    });
  });
  imageList.value.forEach((image) => {
    fileList.push({
      id: image.id,
      name: image.name,
      isImage: image.isImage,
      size: image.size,
      url: image.url
    });
  });
  let data = {
    context: context.value,
    attachments: fileList,
    rollBackId: rollBackId.value
  };
  console.log(data)
  emit("ok", data, props.type);
  visible.value = false;
};

const selected = (select) => {
  let userInfoList = []
  for (let val of select) {
    let userInfo = {
      id: val.id,
      name: val.name,
      avatar: val.avatar,
    }
    userInfoList.push(userInfo)
  }
  userList.value = userInfoList
  console.log('select',userList.value)
}
const delDept = (i) => {
  userList.value.splice(i, 1)
}
defineExpose({
  show
})
</script>

<style lang="scss" scoped>
.userStyle {
  width: 45px;
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  position: relative;
  margin-right: 10px;

  span:first-child {
    position: absolute;
    right: -3px;
    top: -11px;
    cursor: pointer;
  }

  span:last-child {
    text-align: center;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden
  }
}

.custom-dialog {
  :deep .el-dialog__header {
    padding: 10px 20px;

    .el-dialog__title {
      font-size: 17px;
    }

    .el-dialog__headerbtn {
      top: 15px;

      .i {
        font-size: large;
      }
    }
  }

  :deep .el-dialog__footer {
    padding: 10px 20px;
  }
}

.border {
  :deep .el-dialog__header {
    border-bottom: 1px solid #e8e8e8;
  }

  :deep .el-dialog__footer {
    border-top: 1px solid #e8e8e8;
  }
}

:deep .el-select .el-input__inner {
  height: 32px;
  line-height: 32px;
}

:deep .el-select .el-input .el-select__caret {
  line-height: 32px;
}

:deep .el-upload--picture-card {
  width: 65px;
  height: 65px;
  line-height: 70px;
}

:deep .el-upload-list--picture-card {
  .el-upload-list__item {
    width: 65px !important;
    height: 65px !important;
  }
}

:deep .el-upload-list__item-status-label {
  display: block;
}
</style>
