<template>
  <!-- 分享对话框 -->
  <el-dialog
    title="分享文件"
    :visible.sync="visible"
    :close-on-click-modal="false"
    width="680px"
    @close="handleDialogCancel"
  >
    <el-form
      v-show="!shareIsSuccess"
      class="share-file-form"
      :model="form"
      ref="shareFileForm"
      label-suffix="："
      label-width="180px"
      :label-position="screenWidth <= 520 ? 'top' : 'right'"
      :rules="rules"
    >
      <el-form-item label="分享给部门或个人" prop="shareType">
        <el-radio-group v-model="form.shareType">
          <el-radio :label="0">分享到公共社区</el-radio>
          <el-radio :label="1">分享到部门</el-radio>
          <el-radio :label="2">分享到个人</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="getChooseDataLabel"
        v-if="form.shareType == 1 || form.shareType == 2"
      >
        <el-tree
          v-if="form.shareType == 1"
          class="tree-border"
          :data="deptOptions"
          show-checkbox
          default-expand-all
          ref="dept"
          node-key="id"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
        <PaginationSelector
          v-if="form.shareType == 2"
          @pageNationChange="pageNationChange"
          @change="handleChangUserName"
          :optionSource="userListAllByLocal"
          v-model="userIds"
          labelKey="userName"
          valueKey="userId"
          :paginationOption="setSelectPage"
        />
        <!-- {{ userListAllByLocal }} -->
        <!-- <div v-if="form.shareType == 2">人员列表</div> -->
      </el-form-item>
      <el-form-item label="链接有效期至" prop="endTime">
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          placeholder="选择日期时间"
          align="right"
          value-format="yyyy-MM-dd HH:mm:ss"
          :editable="false"
          :clearable="false"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否需要提取码" prop="shareType">
        <el-radio-group v-model="form.isNeedCode">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-form
      v-if="shareIsSuccess"
      class="share-success-form"
      :model="shareData"
      ref="shareSuccessForm"
      label-suffix="："
      label-width="90px"
      :label-position="screenWidth <= 520 ? 'top' : 'right'"
    >
      <div class="success-tip">
        <i class="el-icon-success"></i>
        <span class="text">成功创建分享链接</span>
      </div>
      <el-form-item label="分享链接" prop="shareBatchNum">
        <el-input
          :value="$file.getShareLink(shareData.shareBatchNum)"
          :readonly="true"
          type="textarea"
          autosize
        ></el-input>
      </el-form-item>
      <el-form-item label="提取码" prop="extractionCode">
        <el-input
          v-model="shareData.extractionCode"
          :readonly="true"
        ></el-input>
      </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"
          :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, listUser } from "@/api/system/user";
import PaginationSelector from "@/components/PaginationSelector";
export default {
  name: "ShareFileDialog",
  components: {
    PaginationSelector,
  },
  data() {
    return {
      visible: false, //  对话框是否可见
      // 分享文件对话框数据
      form: {
        isNeedCode: 0, //是否需要提取码，0-是 1-否
        endTime: "",
        shareType: 0, //分享类型 0公共分享，1部门分享，2个人分享
      },
      rules: {
        shareType: [
          { required: true, message: "请选择分享类别", trigger: "blur" },
        ],
        endTime: [
          { required: true, message: "请选择链接有效期", trigger: "blur" },
        ],
      },
      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集合,用于绑定数据
      userIdsParams: "", //用户id集合，用于提交给后台
      userListAllByLocal: [],
      userListAllPaged: [],
    };
  },
  computed: {
    // 屏幕宽度
    screenWidth() {
      return store.state.common.screenWidth;
    },
    getChooseDataLabel() {
      if (this.form.shareType == 1) {
        return "选择部门";
      } else if (this.form.shareType == 2) {
        return "选择个人";
      }
    },
  },
  watch: {
    "form.shareType"(value) {
      if (value == 1) {
        this.getDeptTree();
        // 清空人员的选择
        this.clearCheckedUser();
      } else if (value == 2) {
        this.getUserList();
        // 清空部门的选择
        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.userIdsParams;
      }
      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.shareData = res.data;
                this.shareIsSuccess = true;
                this.callback("confirm");
              } else {
                this.$message.error(res.message);
              }
            })
            .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);
    },

    //获取下拉框中的运动员编号--保存方案
    handleChangUserName(val) {
      this.userIdsParams = val.join(",");
    },

    // 清空选中的人员
    clearCheckedUser() {
      this.userIds = "";
      this.userIdsParams = "";
    },
    // 清空组织的选择
    clearCheckedDept() {
      if (this.$refs.dept) {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    //查询所有用户列表
    getUserList(setSelectPage) {
      const { pageNum, pageSize } = this.setSelectPage;
      const params = { pageNum, pageSize };
      listUser(params).then((res) => {
        //下拉列表数据源绑定
        this.userListAllByLocal = res.rows;
        //绑定总记录数
        this.setSelectPage.total = res.total;
        //
        if (this.userListAllPaged.length === 0) {
          this.userListAllPaged = res.rows;
        } else {
          //追加数据
          for (let i = 0; i < res.rows.length; i++) {
            this.userListAllPaged.push(res.rows[i]);
          }
        }
      });
    },
  },
};
</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;
  }
}
</style>
