<template>
  <div>
    <b-container style="width: 1200px; height: 735px">
      <b-row>
        <b-col cols="6">
          <div style="margin-bottom: 10px; font-size: 20px; font-weight: bold">
            內部人員({{ internalMembers.length }})
          </div>
          <b-table
            class="email-table"
            :items="staffs"
            :fields="fields1"
            select-mode="multi"
            responsive="sm"
            ref="selectableEmailTable"
            selectable
            sticky-header
            head-variant="light"
            @row-selected="rowSelected"
            borderless
          >
            <template #head()="{ label }">
              <span
                style="font-weight: normal; color: black; font-size: 15px"
                >{{ label }}</span
              >
            </template>
             <template #cell(selected)="{ rowSelected }">
              <template v-if="rowSelected">
                <span aria-hidden="true">&check;</span>
                <span class="sr-only">Selected</span>
              </template>
              <template v-else>
                <span aria-hidden="true">&nbsp;</span>
                <span class="sr-only">Not selected</span>
              </template>
            </template>
          </b-table>
          <hr
            style="
              border-top: 1px solid gray;
              margin-top: 20px;
              margin-bottom: 0;
            "
          />

          <b-row style="margin-top: 20px">
            <b-col cols="4" style="padding-right: 0">
              <b-row style="padding-left: 20px">
                <div style="margin-top: 9px; font-size: 16px; text-align: left">
                  Email :
                </div>
              </b-row>
              <b-row style="padding-left: 20px">
                <div
                  style="margin-top: 20px; font-size: 16px; text-align: left"
                >
                  <a>人員名稱 :</a>
                  <a style="color: red">(非必填)</a>
                </div>
              </b-row>
            </b-col>
            <b-col cols="6">
              <b-row>
                <b-input
                  style="width: 90%; height: 90%; margin-bottom: 10px"
                  v-model="manualEntry"
                >
                </b-input>
              </b-row>
              <b-row>
                <b-input
                  style="width: 90%; height: 90%"
                  v-model="nameManualEntry"
                >
                </b-input>
              </b-row>
            </b-col>
            <b-col cols="2" style="padding: 0">
              <b-button
                class="btn"
                style="margin-top: 28px"
                @click="addList(manualEntry, nameManualEntry)"
                >加入列表
              </b-button>
            </b-col>
          </b-row>

          <b-row style="margin-bottom: 10px">
            <b-col>
              <div
                style="
                  margin-top: 10px;
                  margin-bottom: 10px;
                  font-size: 20px;
                  font-weight: bold;
                "
              >
                外部人員({{ externalMembers.length }})
              </div>
              <b-table
                class="select-table"
                sticky-header
                striped
                responsive="sm"
                head-variant="light"
                :fields="fields2"
                :items="externalMembers"
                borderless
              >
                <template #head()="{ label }">
                  <span
                    style="font-weight: normal; color: black; font-size: 15px"
                    >{{ label }}</span
                  >
                </template>
                <template v-slot:cell(delete)="row">
                  <b-button
                    @click="removeItem(row.item)"
                    size="sm"
                    style="background-color: red"
                    class="float-right"
                  >
                    <b-icon icon="trash-fill"></b-icon>
                  </b-button>
                </template>
              </b-table>
            </b-col>
          </b-row>
        </b-col>

        <b-col cols="6" style="border-left: 1px solid rgba(192, 192, 192)">
          <b-form-group
            label-cols-sm="4"
            label-align-sm="left"
            label="選擇公文種類 :"
            label-for="input-default"
            style="width: 100%"
          >
            <!-- issue_ receive true是收文的 false是發文 -->
            <b-form-select
              v-if="issue_receive"
              :options="receive_document_classifications"
              v-model="receive_document_classification"
            >
            </b-form-select>
            <b-form-select
              v-else
              :options="issue_document_classifications"
              v-model="issue_document_classification"
            >
            </b-form-select>
          </b-form-group>

          <b-form-group
            label-cols-sm="2"
            label-align-sm="left"
            label="主旨:"
            label-for="input-lg"
            style="padding-top: 20px"
          >
            <b-form-textarea
              id="textarea"
              v-model="subject"
              rows="6"
              no-resize
              style="width: 98%; margin-left: 1px"
            >
            </b-form-textarea>
          </b-form-group>
          <!-- 收文內容格式 -->
          <b-form-group
            v-if="issue_receive"
            label-cols-sm="2"
            label-align-sm="left"
            label="內容:"
            label-for="input-lg"
          >
            <b-form-textarea
              id="textarea"
              v-model="content"
              rows="10"
              no-resize
              style="width: 98%; margin-left: 1px"
            >
            </b-form-textarea>
          </b-form-group>
          <!-- 發文內容格式 -->
          <b-form-group
            v-else
            label-cols-sm="2"
            label-align-sm="left"
            label="內容:"
            label-for="input-lg"
          >
            <b-form-textarea
              id="textarea"
              v-model="content"
              rows="17"
              no-resize
              style="width: 98%; margin-left: 1px"
            >
            </b-form-textarea>
          </b-form-group>
          <div v-show="issue_receive">
            <div
              style="
                font-size: 17px;
                font-weight: 800;
                color: #5e72e4;
                margin-bottom: 0px;
              "
            >
              <div style="float: left; padding-top: 10px">
                <a> 附件 </a>
                <a style="color: red; font-size: 13px"> *傳送至外部人員使用 </a>
              </div>
              <div style="float: right">
                <b-button
                  v-show="deleteRelatedDocument === false"
                  @click="deleteRelatedDocument = true"
                  variant="danger"
                  class="m-1 p-1 float-right"
                  >刪除</b-button
                >
                <b-button
                  v-show="deleteRelatedDocument === true"
                  @click="deleteRelatedDocument = false"
                  variant="danger"
                  class="m-1 p-1 float-right"
                  >返回</b-button
                >
                <b-button
                  v-show="issue_receive"
                  variant="primary"
                  class="m-1 p-1 float-right"
                  @click="uploadFileReceive"
                  >上傳附件</b-button
                >
              </div>
            </div>

            <div
              id="AAA"
              style="
                height: 110px;
                width: 100%;
                overflow: auto;
                margin-top: 15px;
              "
            >
              <hr
                style="
                  border-top: 1px solid gray;
                  margin-top: 0;
                  margin-bottom: 0;
                "
              />
              <div style="padding-top: 10px">
                <ul
                  class="pl-2"
                  style="
                    list-style-type: none;
                    font-weight: 600;
                    font-size: 14px;
                  "
                >
                  <div v-for="(file, index) in selectedFiles" :key="index">
                    <b-row style="margin-right: 15px">
                      <b-col cols="7">
                        <a
                          class="mb-2"
                          style="
                            display: block;
                            overflow: hidden;
                            white-space: nowrap;
                            text-overflow: ellipsis;
                          "
                          :href="file.src"
                          target="_blank"
                        >
                          • {{ file.name }}
                        </a>
                      </b-col>
                      <b-col cols="5">
                        <b-badge variant="info" style="padding-bottom: 5px">{{
                          new Date(file.uploadTime).toLocaleString("zh-TW", {
                            dateStyle: "long",
                            timeStyle: "short",
                            hour12: false,
                          })
                        }}</b-badge>
                        <b-button
                          @click="deleteFile(file)"
                          v-if="deleteRelatedDocument === true"
                          size="sm"
                          variant="danger"
                          class="float-right btn_delete"
                        >
                          <b-icon icon="trash-fill"></b-icon>
                        </b-button>
                      </b-col>
                    </b-row>
                  </div>
                </ul>
              </div>
            </div>
          </div>
          <div class="btns1">
            <b-button class="btn_send" @click="sendEmail" data-dismiss="modal">
              傳送
            </b-button>
          </div>
        </b-col>
      </b-row>
    </b-container>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import Multiselect from 'vue-multiselect'
import 'vue-multiselect/dist/vue-multiselect.min.css'
import uploadFile from '@/views/DocumentManagement/ModalContent/uploadFile.vue'

export default {
  props: ['selectedFiles'],
  data () {
    return {
      selectedOutsideStaff: [],
      deleteRelatedDocument: false,
      subject: '',
      content: '',
      emailInput: '',
      manualEntry: '',
      nameManualEntry: '',
      fields1: [
        {
          key: 'selected',
          label: '選取',
          thStyle: { width: '15%' }
        },
        {
          key: 'name',
          label: '人員',
          thStyle: { width: '20%' }
        },
        {
          key: 'email',
          label: '電子郵件',
          thStyle: { width: '55%' }
        }
      ],
      fields2: [
        {
          key: 'name',
          label: '人員',
          thStyle: { width: '20%' }
        },
        {
          key: 'email',
          label: '電子郵件',
          thStyle: { width: '55%' }
        },
        {
          key: 'delete',
          label: '刪除',
          thStyle: { width: '10%' }
        }
      ],
      receive_document_classifications: [
        { text: '送審文件', value: '送審文件' },
        { text: '會議通知', value: '會議通知' },
        { text: '其他', value: '其他' }
      ],
      issue_document_classifications: [
        { text: '函(稿)', value: '函(稿)' },
        { text: '書函(稿)', value: '書函(稿)' },
        { text: '備忘錄(稿)', value: '備忘錄(稿)' },
        { text: '開會通知(稿)', value: '開會通知(稿)' },
        { text: '會議記錄(稿)', value: '會議記錄(稿)' }
      ],
      receive_document_classification: '送審文件',
      issue_document_classification: '函(稿)',
      issue_receive: true,
      staffs: [],
      // selectedMember: [],
      internalMembers: [],
      externalMembers: [],
      UploadFileModalOpen: false,
      SendToEmailSelectModalOpen: true,
      arr: [
        {
          email: '407380202@gms.tku.edu.tw',
          name: '蔡旻潔',
          substitute: {
            name: '蔡旻潔',
            _id: '"6238954f922af57528d70d37"'
          },
          _id: '6238954f922af57528d70d37'
        }
      ]
    }
  },
  async mounted () {
    if (this.$route.name === 'PaperReceiveCreate') {
      this.issue_receive = true
    } else if (this.$route.name === 'PaperPostCreate') {
      this.issue_receive = false
    }
    this.staffs = await this.$store.dispatch('project/lookupStaffs', {
      selects: ['_id', 'name', 'email']
    })
    if (this.issue_receive) {
      // 收文
      switch (this.receive_document_classification) {
        case '送審文件':
          this.subject = `統包商已提送相關文件，煩請進行審查並於規定期限提送相關審查意見給彙整人員，謝謝！(${this.officialDoc.subject})`
          this.content = `統包商已提送相關文件，煩請進行審查並於規定期限提送相關審查意見給彙整人員，謝謝！
${this.officialDoc.subject}`
      }
    } else {
      // 發文
      this.subject = `【${this.issue_document_classification}】${this.officialDoc.subject}`
    }
    console.log(this.$refs.selectableEmailTable)
    this.$refs.selectableEmailTable.selectRow(2)
    // if (this.selectedFiles) {
    //   let arr = []
    //   arr = localStorage.getItem('files')
    //   arr.push(this.selectedFiles)
    //   localStorage.setItem('files', arr)
    // }
  },
  methods: {
    ...mapActions('officialDocument', ['addRecord']),
    async addList (email, name) {
      if (email === '') alert('尚未輸入Email!')
      else {
        let item = {
          name: name || '外部人員',
          email: email
        }
        this.externalMembers.push(item)
        // let arr = []
        // arr = this.externalMembers
        // arr.push(item)
        // localStorage.setItem('externalMembers', JSON.stringify(arr))
        this.manualEntry = ''
        this.nameManualEntry = ''
      }
      // for (let i = 0; i < this.arr.length; i++) {
      //   const element = this.arr[i]
      //   const index = this.staffs.findIndex(item => item._id === element._id)
      //   console.log(index)
      //   this.$refs.selectableEmailTable.selectRow(index)
      // }
    },
    rowSelected (items) {
      this.internalMembers = items
      // localStorage.setItem('internalMembers', JSON.stringify(items))
    },
    removeItem (item) {
      for (var i = 0; i < this.externalMembers.length; i++) {
        if (this.externalMembers[i].email === item.email) {
          this.externalMembers.splice(i, 1)
        }
      }
    },
    uploadFileReceive () {
      this.$emit('uploadFileReceive')
    },
    deleteFile (item) {
      if (!confirm('確定刪除此文件嗎?')) return
      for (var i = 0; i < this.selectedFiles.length; i++) {
        if (this.selectedFiles[i]._id === item._id) {
          this.selectedFiles.splice(i, 1)
        }
      }
      alert('已刪除')
    },
    async uploadFile () {
      this.UploadFileModalOpen = true
    },
    async sendEmail () {
      console.log(this.currentUser);
      const email = this.currentUser.email
      const emailPass = this.currentUser.emailPass
      // eslint-disable-next-line camelcase
      const emailSubject = this.subject
      const content = this.content
      console.log(this.currentProject.name)
      const projectName = this.currentProject.name
      // this.currentProject.name
      var wasNull = false
      if (
        emailPass === ''
      ) {
        wasNull = true
      }
      if (wasNull) alert('SMTP密碼錯誤或空白！請聯繫系統管理員')
      else {
        if (this.selectedMember.length !== 0) {
          if (this.officialDoc.distinguish === '來文') {
            let toUserList
            if (this.internalMembers.length !== 0) {
              toUserList = this.internalMembers.map(member => member.email)
              await this.$store.dispatch('officialDocument/sendEmail', {
                email,
                emailPass,
                emailSubject,
                content,
                toUserList,
                distinguish: 0,
                url: `${process.env.WEB_ROOT_URL}${this.$route.fullPath}`
              })
            }
            if (this.externalMembers.length !== 0) {
              toUserList = this.externalMembers.map(member => member.email)
              await this.$store.dispatch('officialDocument/sendEmail', {
                email,
                emailPass,
                emailSubject,
                content,
                toUserList,
                distinguish: 2,
                attachments: this.selectedFiles.map(item => {
                  return {
                    filename: item.name,
                    path: item.src
                  }
                })
              })
            }
          } else if (this.officialDoc.distinguish === '發文') {
            let toUserList = this.selectedMember.map(member => member.email)
            await this.$store.dispatch('officialDocument/sendEmail', {
              projectName,
              email,
              emailPass,
              emailSubject,
              content,
              toUserList,
              fileName: this.officialDoc.document_type,
              fileContent: this.officialDoc,
              document_type: this.issue_document_classification,
              distinguish: 1
            })
          } else {
            alert('你來到未知道公文領域')
          }
          await this.addRecord({
            staffName: this.currentUser.name,
            todo: `Email傳送成功|${this.internalMembers
              .map(item => item.name)
              .join('、')}|${this.externalMembers
              .map(item => (item.name === '外部人員' ? item.email : item.name))
              .join('、')}`
          })
          this.$emit('update:selectedFiles', [])
          localStorage.getItem('internalMembers') && localStorage.removeItem('internalMembers')
          localStorage.getItem('externalMembers') && localStorage.removeItem('externalMembers')
          localStorage.getItem('files') && localStorage.removeItem('files')
          alert('傳送成功！')
          this.$emit('closeEvent')
        } else {
          alert('請選擇人員！')
        }
      }
    },
    selectRowaaa () {
      console.log(this.arr)
      for (let i = 0; i < this.arr.length; i++) {
        const element = this.arr[i]
        const index = this.staffs.findIndex(item => item._id === element._id)
        console.log(index)
        this.$refs.selectableEmailTable.selectRow(index)
      }
    }
  },
  computed: {
    ...mapState({
      officialDoc: state => state.officialDocument.officialDoc,
      currentUser: state => state.user.current,
      currentProject: state => state.project.current,
      enums: state => state.enums
    }),
    selectedMember () {
      return this.internalMembers.concat(this.externalMembers)
    }
 },
  components: {
    Multiselect,
    uploadFile
  }
}
</script>
<style>
.card-header {
  background-color: rgba(192, 192, 192, 0.308);
  border-bottom: 1px solid rgba(2, 2, 2, 0.055);
  padding-top: 15px;
}
</style>
<style scoped>
.select-table {
  width: 100%;
  height: 215px !important;
  overflow-y: scroll;
  margin-top: 10px;
  text-align: center;
  margin-top: 0;
  margin-bottom: 0;
  border-top: 1px solid;
  border-left: 1px solid;
  border-bottom: 1px solid;
  border-color: rgb(236, 236, 236);
}
.white-bg {
  background-color: rgb(236, 236, 236);
}
.email-table {
  width: 100%;
  height: 300px !important;
  overflow-y: scroll;
  margin-top: 10px;
  text-align: center;
  margin-top: 0;
  margin-bottom: 0;
  border-top: 1px solid;
  border-left: 1px solid;
  border-bottom: 1px solid;
  border-color: rgb(236, 236, 236);
}
.form-control {
  color: black;
}
.custom-select {
  color: black !important;
  box-shadow: none;
  -webkit-box-shadow: none;
}
.btns1 {
  float: right;
  margin-right: 0%;
}
.btn {
  background-color: rgb(75, 102, 255);
  font-size: 13px;
  margin-right: 10px;
  padding-left: 7px;
  padding-right: 7px;
  padding-top: 5px;
  padding-bottom: 5px;
  color: #ffffff;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
  border: none;
}
.btn:hover {
  color: rgb(255, 255, 255);
  background-color: rgb(49, 68, 175);
}
.btn_send {
  background-color: rgb(75, 102, 255);
  font-size: 16px;
  margin-right: 10px;
  padding-left: 7px;
  padding-right: 7px;
  padding-top: 5px;
  padding-bottom: 5px;
  color: #ffffff;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
  border: none;
}
.btn_send:hover {
  color: rgb(255, 255, 255);
  background-color: rgb(49, 68, 175);
}
.btn_delete {
  background-color: rgb(255, 0, 0);
  font-size: 12px;
  padding: 4px 6px;
  color: #ffffff;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
  border: none;
}
.btn_delete:hover {
  color: rgb(255, 255, 255);
  background-color: rgb(199, 0, 0);
}
</style>
