<!-- 用户编辑弹窗 -->
<template>
  <el-form ref="form" :model="form" label-width="82px" :disabled="true">
    <el-row :gutter="15">
      <el-col :span="6">
        <el-form-item label="主题" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="发布人" prop="releaseUserName">
          <el-input v-model="form.releaseUserName"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="发布时间" prop="releaseTime">
          <el-date-picker
            v-model="form.releaseTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 60%"
          >
          </el-date-picker>
          <el-checkbox
            style="margin-left: 5px"
            v-model="form.isTimeRelease"
            :true-label="1"
            :false-label="0"
            >按照发布时间进行计划发布</el-checkbox
          >
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="失效时间" prop="failureTime">
          <el-date-picker
            v-model="form.failureTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="创建时间" prop="createTime">
          <el-input v-model="form.createTime" style="width: 60%"> </el-input>
          <el-checkbox
            style="margin-left: 5px"
            v-model="form.isAuthority"
            :true-label="1"
            :false-label="0"
            >到失效时间自动回收权限</el-checkbox
          >
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="发布说明" prop="remark">
          <el-input v-model="form.remark" type="textarea"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="发布文档" prop="fileList">
          <ele-pro-table
            ref="table"
            :columns="columns"
            :datasource="fileList"
            tool-class="ele-toolbar-form"
            cache-key="systemOrgUserTable"
            :needPage="false"
          >
            <template v-slot:action="{ row }">
              <el-link
                type="primary"
                :underline="false"
                icon="el-icon-edit"
                @click="browseOpen(row, 1)"
                v-if="['docx', 'pdf', 'doc'].includes(row.storagePath[0]?.type)"
              >
                签章
              </el-link>
              <el-link
                type="primary"
                :underline="false"
                icon="el-icon-edit"
                @click="browseOpen(row, 2)"
                v-if="
                  !['docx', 'pdf', 'doc'].includes(row.storagePath[0]?.type)
                "
              >
                预览
              </el-link>
            </template>
          </ele-pro-table>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="通知用户" prop="storagePath">
          <power
            height="200px"
            :powerArr="powerArr"
            :isSave="false"
            ref="powerRef"
          />
        </el-form-item>
      </el-col>
    </el-row>
    <sealManagement ref="sealManagementRef" @save="save"></sealManagement>
    <browse ref="browseRef"></browse>
  </el-form>
</template>

<script>
  import power from './power.vue';
  import {
    sendGetById,
    fileUpdateAPI,
    getById
  } from '@/api/bpm/components/doc';
  import { uploadFileNew } from '@/components/addDoc/api/index.js';
  import sealManagement from '@/components/addDoc/sealManagement.vue';
  import browse from '@/components/addDoc/browse.vue';
  import { usageRecordAdd } from '@/api/bpm/components/sealManagement';

  const defaultForm = {
    name: '', //名称
    fileList: [], //文档集合json
    userAuthority: [], //用户权限集合json
    releaseTime: '', //发布时间
    failureTime: '', //失效时间
    isAuthority: '', //是否回收权限 0 1
    remark: ''
  };
  export default {
    components: { power, browse, sealManagement },
    props: {
      businessId: {
        default: ''
      }
    },
    data() {
      return {
        fileList: [],
        form: {
          ...defaultForm
        },

        columns: [
          {
            label: '编码',
            prop: 'code',
            width: 180,
            align: 'center',
            fixed: 'left',
            showOverflowTooltip: true
          },
          {
            prop: 'name',
            label: '文档名称',
            align: 'center',
            slot: 'name',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            prop: 'storagePath',
            label: '文件名称',
            align: 'center',

            showOverflowTooltip: true,
            minWidth: 200,
            formatter: (_row, _column, cellValue) => {
              return cellValue[0]?.name;
            }
          },
          {
            prop: 'version',
            label: '版本',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },

          {
            prop: 'createUserName',
            label: '创建人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 160,
            formatter: (_row, _column, cellValue) => {
              return this.$util.toDateString(cellValue);
            }
          },
          {
            prop: 'updateUserName',
            label: '修改人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: 'updateTime',
            label: '修改时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 160
          },
          {
            prop: 'sizeUnit',
            label: '文档大小',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: '',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 150,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ],

        powerArr: [
          { name: 'visible', label: '可见' },
          { name: 'check', label: '查看' },
          { name: 'browse', label: '浏览' },

          { name: 'download', label: '下载' },
          { name: 'print', label: '打印' }
        ]
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      }
    },
    created() {
      this.init();
    },
    methods: {
      save({ pdfFile, id, droppedImages }) {
        let fileDataIndex = this.fileList.findIndex((item) => item.id == id);
        this.$set(this.fileList[fileDataIndex], 'pdfFile', pdfFile);
        this.$set(this.fileList[fileDataIndex], 'droppedImages', droppedImages);
      },
      async getTableValue() {
        // 处理包含 pdfFile 的文件，上传并更新文档地址
        const uploadPromises = this.fileList
          .filter((item) => item.pdfFile)
          .map(async (item) => {
            // 上传 PDF 文件
            const uploadRes = await uploadFileNew({
              module: 'fm',
              multiPartFile: item.pdfFile
            });
            // 获取文件地址
            const fileUrl = uploadRes.data;
            // 更新文档地址
            await fileUpdateAPI({
              stampStoragePath: [fileUrl],
              id: item.id
            });
            // 处理签章使用记录
            if (item.droppedImages && item.droppedImages.length) {
              item.droppedImages.forEach((dropItem) => {
                if (dropItem.imgId) {
                  usageRecordAdd({
                    sealId: dropItem.imgId,
                    sealName: dropItem.name,
                    version: dropItem.version,
                    documentCode: item.code,
                    documentName: item.name,
                    usageObjectId: item.id,
                    usageObjectName: item.name,
                    usageDeptName: this.$store.state.user.info.groupName,
                    usageDeptId: this.$store.state.user.info.groupId,
                    userName: this.$store.state.user.info.name,
                    userId: this.$store.state.user.info.userId,
                    useTime: new Date()
                  });
                }
              });
            }
          });

        await Promise.all(uploadPromises);
        return 2;
      },
      async init() {
        const data = await sendGetById(this.businessId);
        this.form = data;
        this.fileList = data.fileList.map((item) => {
          item['droppedImages'] = '';
          item['pdfFile'] = '';
          return item;
        });

        this.$nextTick(() => {
          this.$refs.powerRef &&
            this.$refs.powerRef.setTableList(data.userAuthority);
        });
      },
      async browseOpen(row, type) {
        if (type == 1) {
          let data = await getById(row.id);
          this.$refs.sealManagementRef.open({
            ...data,
            droppedImages: row.droppedImages
          });
        } else {
          this.$refs.browseRef.open(await getById(row.id));
        }
      }
    }
  };
</script>
<style scoped lang="scss"></style>
