<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    width="500px"
    :visible.sync="showEditFlag"
    :close-on-click-modal="false"
    custom-class="ele-dialog-form"
    append-to-body
    @close="cancel"
    :title="title"
    ref="Emodal"
    :maxable="true"
    :resizable="true"
  >
    <el-tabs
      v-model="activeName"
      type="card"
      @tab-click="handleClick"
      style="margin-bottom: 10px"
    >
      <el-tab-pane label="文档工作区" name="1"></el-tab-pane>
      <el-tab-pane label="个人文档" name="2"></el-tab-pane>
    </el-tabs>
    <el-form ref="form" :model="form" :rules="rules" label-width="82px">
      <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="文档位置" prop="directoryId">
            <el-cascader
              style="width: 100%"
              v-model="form.directoryId"
              :options="folderList"
              @change="initFileCode"
              ref="cascaderRef"
              :props="{
                value: 'id',
                label: 'name',
                children: 'sonDirectoryList',
                emitPath: false,
                checkStrictly: true
              }"
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="编码分类" prop="codeType">
            <ele-tree-select
              clearable
              :data="list"
              v-model="form.codeType"
              placeholder="请选择"
              default-expand-all
              labelKey="name"
              childrenKey="sonDirectoryList"
              valueKey="id"
              @change="typeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="编码方案" prop="businessCodeId">
            <el-select
              v-model="form.businessCodeId"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="文档类型" prop="type">
            <DictSelection
              dictName="文档类型"
              v-model="form.type"
            ></DictSelection>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="文档" prop="storagePath">
            <div style="display: flex; align-items: center">
              <fileUpload
                v-model="form.storagePath"
                module="main"
                :limit="100"
                :multiple="true"
                @fileChange="fileChange"
              >
              </fileUpload>
            </div>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="form.remark"
              type="textarea"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="save">
        确认
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import {
    fileSaveAPI,
    selectTreeList,
    listParentId,
    getDocTreeListAPI,
    listCode
  } from './api/index';
  import FileUpload from './fileUpload.vue';
  import { setFolderList } from './util.js';
  import { mapGetters } from 'vuex';
  export default {
    components: { FileUpload },
    props: {
      isDefaultPersonal: {
        type: Boolean,
        default: false
      }
    },

    data() {
      const defaultForm = {
        name: '', //名称
        type: '1', //类型
        sizeUnit: '', //大小，
        unit: '', //单位
        remark: '', //备注
        status: '', //状态
        storagePathId: '',
        directoryId: '',
        businessCodeId: '',
        storagePath: [],
        id: '',
        lcyStatus: 1,
        fileType: 0
      };
      return {
        activeName: '1',
        rules: {
          businessCodeId: [
            { required: true, message: '请选择', trigger: 'blur' }
          ],
          // codeType: [{ required: true, message: '请选择', trigger: 'blur' }],
          directoryId: [{ required: true, message: '请选择', trigger: 'blur' }],
          storagePath: [{ required: true, message: '请选择', trigger: 'blur' }]
        },
        templateVisible: false,
        folderList: [],
        allFolderList: [],
        myFolderList: [],
        list: [],
        options: [],
        defaultForm,
        code: '',
        // 表单数据
        form: { ...defaultForm },

        // 提交状态
        loading: false,
        showEditFlag: false,
        title: '',
        type: '新建附件',
        nodeData: {}
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      },
      ...mapGetters(['user'])
    },
    async created() {
      this.allFolderList = await getDocTreeListAPI({
        type: 0,
        currentUserId: this.user.info.userId
      });
      this.myFolderList = await getDocTreeListAPI({
        type: 1,
        currentUserId: this.user.info.userId
      });

      this.activeName = this.isDefaultPersonal ? '2' : '1';
      console.log(this.activeName, 'this.activeName');
      this.folderList = this.activeName == '2' ? this.myFolderList : this.allFolderList;
      setFolderList(this.folderList); //权限过滤
    },
    methods: {
      handleClick() {
        this.form.directoryId = '';
        this.form.businessCodeId = '';
        this.form.codeType = '';
        if (this.activeName == 2) {
          this.folderList = this.myFolderList;
        } else {
          this.folderList = this.allFolderList;
        }

        if(this.isDefaultPersonal && this.activeName == '2') {
          this.form.directoryId = this.folderList[0]?.id || '';
        }
      },
      async getTreeCode() {
        let nodeData = {};
        await this.$nextTick(() => {
          // console.log(this.$refs,'this.$refs')
          nodeData =
            this.$refs.cascaderRef && this.$refs.cascaderRef.getCheckedNodes();
        });
        this.nodeData = {
          id: nodeData[0]?.data?.id,
          parentId:
            nodeData[0]?.data?.parentId != 0 ? nodeData[0]?.data?.parentId : ''
        };
      },
      async initFileCode() {
        console.log('getTreeCode~~~', this.nodeData);
        await this.getTreeCode();
        this.options = this.nodeData.id ? await listCode(this.nodeData) : [];
        if (this.options.length > 0) {
          this.form.businessCodeId = this.options[0].id;
          this.form.codeType = this.options[0].parentId;
        } else {
          this.form.businessCodeId = '';
        }
      },
      async open() {
        this.showEditFlag = true;
        this.$nextTick(async () => {
          this.list = await selectTreeList();
          if(this.isDefaultPersonal && this.activeName == '2') {
            this.form.directoryId = this.folderList[0]?.id || '';
          }
          await this.initFileCode();
          this.setTree(this.list);
        });
      },

      setTree(data) {
        data.forEach((item) => {
          item.sonDirectoryList = item.sonDirectoryList.filter(
            (item) => item.type == 1
          );
          if (item.sonDirectoryList.length > 0) {
            this.setTree(item.sonDirectoryList);
          }
        });
      },
      async typeChange(val) {
        let obj = {
          pageNum: 1,
          size: 100,
          parentId: val
        };
        if (this.activeName == 1) {
          obj['objId'] = this.nodeData?.id;
          obj['objParentId'] = this.nodeData?.parentId;
        }
        let data = await listParentId(obj);
        this.options = data.list.filter((item) => item.type == 2);
        this.form.businessCodeId = '';
      },

      fileChange(file) {
        this.form.name = file.name.replace(/\.[^/.]+$/, '');
      },

      /* 保存编辑 */
      save() {
        this.$refs.form.validate(async (valid) => {
          if (!valid) {
            return false;
          }

          let data = {
            ...this.form
          };
          if (this.activeName == 2) {
            data.fileType = 1;
          }
          this.loading = true;
          fileSaveAPI(data)
            .then((msg) => {
              this.loading = false;

              this.cancel();
              this.$emit('done', msg);
            })
            .catch((e) => {
              this.loading = false;
            });
        });
      },

      cancel() {
        this.form = { ...this.defaultForm, directoryId: this.form.directoryId };
        this.$refs.form.clearValidate();
        this.showEditFlag = false;
      }
    }
  };
</script>
<style scoped lang="scss">
  .aaa {
    width: 100%;

    ::v-deep .upload-demo {
      width: 100%;

      .el-upload--text {
        width: 100%;

        button {
          width: 100%;
          background: #ffffff;
          border: 1px solid #dbdbdb;
          border-radius: 5px;
        }
      }

      .el-upload-list {
        transform: translate(10px, -39px);
        position: absolute;
      }
    }
  }
</style>
