<template>
  <!-- 分享对话框 -->
  <el-dialog
    title="分享文件"
    :visible.sync="visible"
    :close-on-click-modal="false"
    width="480px"
    @close="handleDialogCancel"
    top="20vh"
  >
    <el-form
      v-show="!shareIsSuccess"
      class="share-file-form"
      :model="form"
      ref="shareFileForm"
      label-suffix="："
      label-width="160px"
      :rules="rules"
      size="mini"
    >
      <el-form-item label="分享给部门或个人" prop="shareType">
        <el-radio-group v-model="form.shareType">
          <el-radio :label="PUBLIC_SHARE">分享到公共社区（需审核）</el-radio>
          <el-radio :label="DEPT_SHARE">分享到部门（需审核）</el-radio>
          <el-radio :label="PERSONAL_SHARE">分享到个人</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="getChooseDataLabel"
        v-if="form.shareType == DEPT_SHARE || form.shareType == PERSONAL_SHARE"
        prop="deptOrUser"
      >
        <el-tree
          v-if="form.shareType == DEPT_SHARE"
          class="tree-border"
          :data="deptOptions"
          show-checkbox
          default-expand-all
          ref="dept"
          node-key="id"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
        <el-select
          v-if="form.shareType == PERSONAL_SHARE"
          v-model="userIds"
          filterable
          remote
          multiple
          :remote-method="getAllUserListRemote"
          :loading="loading"
          placeholder="请选择人员（支持搜索）"
        >
          <el-option
            v-for="item in options"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button
        v-if="shareIsSuccess"
        type="primary"
        @click="
          $file.copyShareLink(shareData.shareBatchNum, shareData.extractionCode)
        "
        >复制链接及提取码</el-button
      >
      <template v-else>
        <el-button @click="handleDialogCancel">取 消</el-button>
        <el-button
          type="primary"
          :disabled="sureBtnLoading"
          :loading="sureBtnLoading"
          @click="handleDialogSure('shareFileForm')"
          >确 定</el-button
        >
      </template>
    </div>
  </el-dialog>
</template>

<script>
import store from "@/store/index.js";
import { shareFile } from "@/api/qwFile";
import { deptTreeSelect, getAllUserList } from "@/api/system/user";
import PaginationSelector from "@/components/PaginationSelector";
import { shareTypeConstant } from "./constants";
const { DEPT_SHARE, PERSONAL_SHARE } = shareTypeConstant;

export default {
  name: "ShareFileDialog",
  components: {
    PaginationSelector,
  },
  data() {
    const validateDeptOrUser = (rule, value, callback) => {
      if (this.form.shareType == DEPT_SHARE && !this.getDeptAllCheckedKeys()) {
        return callback(new Error("请选择组织"));
      }
      if (this.form.shareType == PERSONAL_SHARE && this.userIds.length == 0) {
        return callback(new Error("请选择人员"));
      }
      return callback();
    };
    return {
      visible: false, //  对话框是否可见
      // 分享文件对话框数据
      form: {
        isNeedCode: "", //是否需要提取码，0-是 1-否 暂不需要
        endTime: "", //暂不需要
        shareType: 0, //分享类型 0公共分享，1部门分享，2个人分享
        shareTo: "",
      },
      rules: {
        shareType: [
          { required: true, message: "请选择分享类别", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "请选择链接有效期", trigger: "blur" },
        ],
        deptOrUser: [
          {
            validator: validateDeptOrUser,
            required: true,
          },
        ],
      },
      sureBtnLoading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              const nowDate = new Date();
              picker.$emit(
                "pick",
                new Date(
                  nowDate.getFullYear(),
                  nowDate.getMonth(),
                  nowDate.getDate(),
                  23,
                  59,
                  59
                )
              );
            },
          },
          {
            text: "1天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "7天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
          {
            text: "30天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit("pick", date);
            },
          },
        ],
      },
      shareIsSuccess: false, //  分享是否成功
      // 分享成功的数据
      shareData: {
        shareBatchNum: "",
        extractionCode: "",
      },
      // 部门列表
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      //分页信息
      setSelectPage: {
        pageSize: 5, //每页显示条数  3条刚好
        pageNum: 1, //当前页
        pagerCount: 5, //按钮数，超过时会折叠
        total: 0, //总条数
      },
      userIds: [], //用户id集合,用于绑定数据
      options: [],
      ...shareTypeConstant,
    };
  },
  computed: {
    // 屏幕宽度
    screenWidth() {
      return store.state.common.screenWidth;
    },
    getChooseDataLabel() {
      if (this.form.shareType == this.DEPT_SHARE) {
        return "选择部门";
      } else if (this.form.shareType == this.PERSONAL_SHARE) {
        return "选择个人";
      }
    },
  },
  watch: {
    "form.shareType"(value) {
      if (value == this.DEPT_SHARE) {
        this.getDeptTree();
        // 清空人员的选择
        this.clearCheckedUser();
      } else if (value == this.PERSONAL_SHARE) {
        this.getAllUserListRemote();
        // 清空部门的选择
        this.clearCheckedDept();
      } else {
        // 选择分享给全部时，要清空部门和人员的所有选择
        this.clearCheckedUser();
        this.clearCheckedDept();
      }
    },
  },
  methods: {
    /**
     * 分享文件对话框 | 取消按钮点击事件
     * @description 关闭对话框，重置表单
     */
    handleDialogCancel() {
      this.$refs["shareFileForm"].resetFields();
      this.visible = false;
      this.callback("cancel");
      // 清空部门和人员的所有选择
      this.clearCheckedUser();
      this.clearCheckedDept();
    },
    /**
     * 分享文件对话框 | 确定按钮点击事件
     * @description 校验表单，校验通过后调用分享文件接口
     * @param {string} formName 表单ref值
     */
    handleDialogSure(formName) {
      if (this.form.shareType == 1) {
        this.form.shareTo = this.getDeptAllCheckedKeys();
      } else if (this.form.shareType == 2) {
        this.form.shareTo = this.userIds.join(",");
      }
      this.sureBtnLoading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          shareFile({
            ...this.form,
            remarks: "",
            userFileIds: this.fileInfo.map((res) => res.userFileId).join(","),
          })
            .then((res) => {
              this.sureBtnLoading = false;
              if (res.code == 200) {
                this.$message.success("分享成功！");
              } else {
                this.$message.error(res.message);
              }
              this.handleDialogCancel();
            })
            .catch(() => {
              this.sureBtnLoading = false;
            });
        } else {
          this.sureBtnLoading = false;
          return false;
        }
      });
    },
    /**
     * 根据角色ID查询部门树结构
     * @param {string} roleId 当前用户角色id
     */
    getDeptTree() {
      // 若已经加载过不再重复调取接口
      if (this.deptOptions.length > 0) {
        return;
      }
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },

    /**
     * 获取被选择的组织id
     * @returns {string} 组织Id以逗号隔开的字符串
     */
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      // let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys.join(",");
    },

    //下拉列表分页的点击的事件
    pageNationChange(val) {
      //设置当前页为点击的页
      this.setSelectPage.pageNum = val;
      //重新调用分页查询的方法
      this.getUserList(this.setSelectPage);
    },
    // 清空选中的人员
    clearCheckedUser() {
      this.userIds = [];
    },
    // 清空组织的选择
    clearCheckedDept() {
      if (this.$refs.dept) {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    //查询远程用户
    getAllUserListRemote(query) {
      if (query !== "") {
        this.loading = true;
        const params = { pageNum: 1, pageSize: 20, userName: query };
        getAllUserList(params).then((res) => {
          this.options = res.rows;
          this.loading = false;
        });
      } else {
        this.options = [];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/varibles.scss";

.success-tip {
  margin-bottom: 16px;
  text-align: center;
  color: $Success;

  .el-icon-success {
    margin-right: 8px;
    height: 20px;
    line-height: 20px;
  }
}

::v-deep .el-radio {
  display: flex;
  margin: 10px 0;
}
</style>
