<template>
  <div>
    <xy-dialog ref="dialog" :width="60" :is-show.sync="isShow" type="form" title="任务归档" :form="form" :rules='rules'
      @submit="submit">
      <template v-slot:title>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>任务名称：
          </div>
          <div class="xy-table-item-content">
            <el-input style="width:400px" v-model="form.title" placeholder="请填写任务名称" autocomplete="off"></el-input>
          </div>
        </div>
      </template>
      <template v-slot:menu_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;">*</span>模块：
          </div>
          <div class="xy-table-item-content">
            <!-- <el-input style="width:400px" v-model="form.menu_id" placeholder="请填写模块" autocomplete="off"></el-input> -->
            <!-- <treeselect :multiple="false" :options="menus" :normalizer="normalizer" placeholder="请选择模块"
              v-model="form.menu_id" /> -->
            <!-- <el-tree
                :data="menus"
                :props="normalizer"
                accordion

                >
              </el-tree> -->
            <el-cascader-panel ref="menu" v-model="selsectMenu" @change="getCheckedNodes" :props="normalizer"
              :options="menus" :show-all-levels="false"></el-cascader-panel>
            <!-- <el-cascader></el-cascader> -->
          </div>
        </div>
      </template>
      <template v-slot:file_ids>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>任务提交附件：
          </div>
          <div class="xy-table-item-content">
            <div v-for="item in otherList">
              <span>{{item.upload_name}}：</span>
              <a :href="item.url">{{item.name}}</a>
              <el-link target="_blank" style="margin:0 10px;" @click="toshowFile(item.url)" type="primary">
                预览
              </el-link>
              <el-link target="_blank" @click="base.downLoadFileUrl(item.id)" type="primary">
                下载
              </el-link>
            </div>
          </div>
        </div>
      </template>
      <template v-slot:file_list>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>最终成果附件：
          </div>
          <div class="xy-table-item-content">
            <el-upload :action="action" class='upload-demo' :file-list="pictureList" ref="pictureUpload"
              style="width:400px" :auto-upload="true" :data="uploadOther" :on-success="handlesuccess"
              :on-remove="handleRemove">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-slot:content>
        <div class="xy-table-item">
          <div class="xy-table-item-label" style="font-weight: bold">
            <span style="color: red;font-weight: 600;padding-right: 4px;"></span>内容归档概述：
          </div>
          <div class="xy-table-item-content">
            <el-input v-model="form.content" :rows='8' type='textarea' placeholder="请输入内容归档概述" clearable
              style="width:400px"></el-input>
            <!-- <tinymce v-model="form.content" ref="tiny" :height="300" /> -->
          </div>
        </div>
      </template>

    </xy-dialog>
    <viewFile ref="viewFile"></viewFile>
  </div>
</template>

<script>
  import {
    getToken
  } from '@/utils/auth'
  import {
    store
  } from "@/api/lawsfile/article.js";
  import {
    save as saveUnit,
    get as getUnit
  } from "@/api/task/unit.js";
  import {
    listregulation
  } from "@/api/lawsfile/regulation.js";
  import Treeselect from "@riophae/vue-treeselect";
  import viewFile from '@/components/viewFile/viewFile.vue'
  // import Tinymce from '@/components/Tinymce'
  export default {
    components: {
      // Tinymce,
      Treeselect,
      viewFile
    },
    data() {
      return {
        isShow: false,
        pictureList: [],
        otherList: [],
        uploadOther: {
          token: ""
        },
        action: `${process.env.VUE_APP_BASE_API}api/admin/upload-file`,
        upload_link: '',
        allMenus: [],
        selsectMenu: [],
        normalizer: {
          label: "name",
          children: "children",
          // checkStrictly: true,
          value: "id",
          expandTrigger: 'hover'
        },
        menus: [],
        form: {
          title: "",
          menu_id: "",
          file_ids: '',
          file_list: '',
          content: '',
          type: 20,
          mission_id: ''
        },
        rules: {
          title: [{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }],
          menu_id: [{
            required: true,
            message: '请选择归属的模块',
            trigger: 'blur'
          }]
        },

      }
    },
    created() {
      this.uploadOther.token = getToken();
      this.getMenus()
    },
    methods: {
      setTitle(e) {
        this.form.title = e.name ? e.name : ''
        this.form.mission_id = e.id ? e.id : ''
        let arr = this.findIdsByNameWithAncestors(this.menus, e.level)
        this.selsectMenu = arr
        this.form.menu_id = arr[1]
        if (e.mission_distribute && e.mission_distribute.length > 0) {
          let _arr = []
          let arr = []
          e.mission_distribute.map(item => {
            if (item.files.length > 0) {
              item.files.map(file => {
                _arr.push({
                  id: file.id,
                  name: file.original_name,
                  url: file.url,
                  upload_name:item.accept_admin.name
                })
                if(item.accept_admin_id===e.main_admin_id){
                  arr.push({
                    id: file.id,
                    name: file.original_name,
                    url: file.url,
                  })
                }
              })

            }
          })
          this.otherList = _arr
          this.pictureList = arr
        }
      },
      async getMenus() {
        var that = this;
        await listregulation(1, 20).then(res => {
          let arr = this.getTreeData(res)
          // item.children = arr;
          this.menus = arr
        }).catch(error => {
          console.log(error)
        })
        // this.menus.map(item=>{

        // })
      },
      toshowFile(url) {
        console.log("url", url)
        this.$refs.viewFile.url = url
        this.$refs.viewFile.diaShow = true
      },
      getCheckedNodes(e) {
        if (e) {
          let nodes = this.$refs.menu.getCheckedNodes()[0].data
          this.form.menu_id = nodes.id
          // this.form.type = nodes.type
          this.$refs.menu.dropDownVisible = false
        }
      },
      getTreeData(data) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].children.length < 1) {
            data[i].children = undefined;
          } else {
            this.getTreeData(data[i].children);
          }
        }
        return data;
      },
      findIdsByNameWithAncestors(arr, level) {
        let results = [];
        for (let item of arr) {
          if (Array.isArray(item.children) && item.children.length > 0) {
            for (let child of item.children) {
              if (child.name === level) {
                results.push(item.id)
                results.push(child.id)
              }
            }
          }
        }
        return results; // 返回扁平化后的结果数组，去掉多余的嵌套
      },
      handleRemove(file, fileList) {
        this.pictureList = fileList
      },
      handlesuccess(response, file, fileList) {
        this.pictureList = fileList
      },
      submit() {
        let _files = []
        if (this.pictureList.length > 0) {
          for (var h of this.pictureList) {
            if (h.response) {
              _files.push(h.response.id)
            } else {
              _files.push(h.id)
            }
          }
          this.form.file_list = _files
        } else {
          this.form.file_list = []
        }

        let _fileids = []
        if (this.otherList.length > 0) {
          for (var h of this.otherList) {
            if (h.response) {
              _fileids.push(h.response.id)
            } else {
              _fileids.push(h.id)
            }
          }
          this.form.file_ids = _fileids
        } else {
          this.form.file_ids = []
        }
        console.log("this.form", this.form)
        // return
        store(this.form).then(response => {
          this.saveUnitStatus()
        }).catch(error => {
          //reject(error)
        })
      },
      saveUnitStatus() {
        saveUnit({
          id: this.form.mission_id,
          audit_status: 5
        }).then(response => {
          this.$Message.success('归档成功');
          this.isShow = false
          this.$emit("reload")
          this.$emit("reloadList")

        }).catch(error => {
          //reject(error)
        })
      },
    },
    watch: {
      isShow(newVal) {
        if (newVal) {

        } else {
          this.pictureList = []
          this.otherList = []
          this.$refs['dialog'].reset()
        }
      },
    },
  }
</script>

<style scoped>
  /deep/ .title,
  /deep/ .menu_id,
  /deep/ .file_list,
    /deep/ .file_ids,
  /deep/ .content {
    flex-basis: 100%;
  }
</style>
