<template>
  <div>
    <div>
      <!-- 按鈕 | 新增作業、返回提審 -->
      <b-row style="padding-left: 15px">
        <!-- <b-button
          class="btn1"
          @click="AssignmentModal()"
          >
        <b-icon-file-earmark-plus />新增作業
      </b-button> -->
        <div>
          <b-button
            @click="backToControl()"
            class="btn1"
            v-show="$route.params.toName == 'Deliver'"
          >
            <b-icon-caret-up />返回提審
          </b-button>
        </div>
      </b-row>
      <modal
        :is-open="AddAssignmentModalOpen"
        title="新增作業"
        @closeEvent="AddAssignmentModalOpen = false"
      >
        <addAssignment @closeEvent="AddAssignmentModalOpen = false" />
      </modal>
    </div>
    <!-- 編輯列表 -->
    <div>
      <b-table
        :items="newDoc.controlWork"
        :fields="fields"
        class="text-center"
        thead-class="thClass"
        small
        responsive="sm"
        ref="selectableTable"
        striped
        bordered
        no-border-collapse
        fixed
        sticky-header="500px"
      >
        <!-- HEAD -->
        <template #head()="{ label }">
          <span style="font-weight: normal; color: white; font-size: 15px">{{
            label
          }}</span>
        </template>
        <!-- 編輯、儲存、刪除 -->
        <template #cell(select)="data">
          <b-icon
            class="btn w-15 p-1"
            icon="cursor"
            aria-hidden="true"
            style="height: 30px; width: auto; margin-left: 5px; color: #1d325f"
            v-if="data.item.isFix === true"
            size="sm"
            @click="patchControlWork(data.index)"
          ></b-icon>
          <!-- <b-button v-if="data.item.isFix === true" size="sm" class="b" @click="patchcontrolwork(data.index)">
            <b-icon-cursor/>
          </b-button> -->
          <b-icon
            class="btn w-15 p-1"
            icon="pencil-square"
            aria-hidden="true"
            style="height: 30px; width: auto; margin-left: 5px; color: #1d325f"
            v-else
            size="sm"
            @click="editControlWork(data.index)"
          ></b-icon>
          <!-- <b-button v-else size="sm" @click="editcontrolwork(data.index)" class="b">
            <b-icon-pencil-square/>
          </b-button> -->
          <!-- <b-button v-else size="sm" @click="edit(data.item._id)" class="b">
            <b-icon-pencil-square/>
          </b-button> -->
          <b-icon
            class="btn w-15 p-1"
            icon="trash"
            aria-hidden="true"
            style="height: 30px; width: auto; margin-left: 5px; color: red"
            size="sm"
            @click="deleteControl(data.item._id)"
          ></b-icon>
          <!-- <b-button size="sm" @click="deleteControl(data.item._id)" class="b">
            <b-icon-trash/>
          </b-button> -->
        </template>
        <!-- 作業項目 -->
        <template #cell(item)="data">
          <!-- <span
            v-if="
              data.item.item == '文件提送作業'
            "
            style="font-weight: bold; color: #04aa6d; font-size: 15px"
          >{{data.value}}</span>
          <span
            v-else-if="
              data.item.item == '文件核定作業'
            "
            style="font-weight: bold; color: blue; font-size: 15px"
          >{{data.value}}</span>
          <span
            v-else
            style="font-weight: bold; color: red; font-size: 15px"
          >{{data.value}}</span> -->
          <b-form-select
            v-model="data.item.item"
            v-if="data.item.isFix"
            :options="getEnumWord('document_controlEnum', data.item.item)"
            class="form-control"
            style="width: 70%; height: 40px; font-size: 15px; text-align: left"
          /><span
            v-else
            style="font-weight: bold; color: black; font-size: 15px"
            >{{ data.value }}</span
          >
        </template>
        <!-- 辦理單位及人員 -->
        <template #cell(responsibilities)="data">
          <b-form-group
            style="
              font-weight: normal;
              color: black;
              font-size: 15px;
              text-align: left;
              margin: auto;
            "
          >
            單位：
            <b-form-input
              type="text"
              v-if="data.item.isFix"
              v-model="data.item.unit"
              class="form-control"
              style="
                width: 70%;
                height: 35px;
                float: right;
                font-size: 15px;
                text-align: left;
                margin-top: -5px;
              "
            /><span v-else>{{ data.item.unit }}</span></b-form-group
          >
          <b-form-group
            style="
              color: black;
              font-size: 15px;
              text-align: left;
              margin: auto;
            "
          >
            人員：
            <b-form-select
              v-model="data.item.manager"
              v-if="data.item.isFix"
              :options="
                staffs.map((staff) => {
                  return { text: staff.name, value: staff.name };
                })
              "
              class="form-control"
              style="
                width: 70%;
                height: 40px;
                float: right;
                font-size: 15px;
                text-align: left;
              "
            /><span v-else>{{ data.item.manager }}</span></b-form-group
          >
        </template>
        <!-- 辦理日期 -->
        <template #cell(processing_date)="data">
          <span
            :title="data.value"
            style="font-weight: normal; color: black; font-size: 15px"
          >
            預定:{{ getFormattedDate(data.item.scheduledDate) }}<br />
            實際:{{ getFormattedDate(data.item.actualDate) }}
          </span>
        </template>
        <!-- 辦理狀態 -->
        <template #cell(status)="data">
          <b-form-select
            :options="getEnumWord('document_statusEnum', data.item.status)"
            v-if="data.item.isFix"
            v-model="data.item.status"
            class="form-control"
            style="width: 70%; height: 40px; font-size: 15px; text-align: left"
          />
          <span
            style="margin: auto; font-weight: normal; color: red; font-size: 15px"
            v-else-if="data.item.status === '待編輯'"
            >
            {{ data.value }}
            </span>
          <span
            style="margin: auto; font-weight: normal; color: black; font-size: 15px"
            v-else
            >
            {{ data.value }}
            </span>
        </template>
        <!-- 版次/文號/備註 -->
        <template #cell(many)="data" style="margin: left; height: 0px">
          <span :title="data.value">
            <b-form-group
              style="
                margin: auto;
                font-weight: normal;
                color: black;
                font-size: 15px;
              "
            >
              版次：
              <b-form-input
                type="text"
                v-if="data.item.isFix"
                v-model="data.item.version"
                class="form-control"
                style="
                  width: 70%;
                  float: right;
                  font-size: 1px;
                  text-align: left;
                  height: 0px;
                "
              />
              <span v-else>{{ data.item.version }}</span></b-form-group
            >
            <b-form-group
              style="
                margin: auto;
                font-weight: normal;
                color: black;
                font-size: 15px;
              "
            >
              文號：<span
                v-if="data.item.officialDocId"
                v-b-popover.hover="{
                  content: `${data.item.officialDocId.issue_text_number}`,
                  placement: 'left',
                  title: '文號',
                }"
                >{{
                  data.item.officialDocId.issue_text_number | ellipsis
                }}</span
              ><span v-else></span>
            </b-form-group>
            <b-form-group
              style="
                margin: auto;
                font-weight: normal;
                color: black;
                font-size: 15px;
              "
            >
              日期：
              <span v-if="data.item.officialDocId"
                >{{ data.item.officialDocId.issue_date }}
              </span>
              <span v-else></span>
            </b-form-group>
            <b-form-group
              style="
                margin: auto;
                font-weight: normal;
                color: black;
                font-size: 15px;
              "
              v-if="data.item.item == '文件審查作業'"
            >
              審查結果：
              <b-form-select
                v-model="data.item.reviewOpinion"
                :options="resultOptions"
                v-if="data.item.isFix"
                class="form-control"
                size="sm"
                style="
                  width: 40%;
                  float: right;
                  text-align: center;
                  font-size: 10px;
                "
              /><span v-else>{{ data.item.reviewOpinion }}</span></b-form-group
            >
            <b-form-group
              style="
                margin: auto;
                font-weight: normal;
                color: black;
                font-size: 15px;
              "
            >
              備註：<b-form-input
                v-model="data.item.note"
                v-if="data.item.isFix"
                type="text"
                class="form-control"
                style="
                  width: 70%;
                  float: right;
                  font-size: 1px;
                  text-align: center;
                "
              /><span v-else>{{ data.item.note }}</span></b-form-group
            >
          </span>
        </template>
        <!-- 檔案 -->
        <template #cell(fileTokens)="data">
          <span
            size="sm"
            @click="pushTo(data.item._id)"
            style="cursor: pointer"
          >
            <span
              :title="data.value"
              style="color: blue; user-select: none; font-weight: normal; font-size: 15px"
            >
              [ {{ data.value.length }} ]
            </span>
          </span>
        </template>
      </b-table>
    </div>
  </div>
</template>

<script>
import addAssignment from '@/views/FileManagement/ModalContent/addAssignment.vue'
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex'
import moment from 'moment'

export default {
  components: {
    modal: () => import('@/views/Modal/index.vue'), // 不用寫在import只需寫在這邊
    addAssignment
  },
  data () {
    return {
      // isFix: false,
      AddAssignmentModalOpen: false,
      staffs: [],
      fields: [
        {
          key: 'select',
          label: '',
          sortable: false,
          tdClass: 'align-middle',
          thStyle: { background: '#1d325f', color: '#ffffff' }
        },
        {
          key: 'item',
          label: '作業項目',
          sortable: false,
          tdClass: 'align-middle',
          thStyle: { background: '#1d325f', color: '#ffffff' }
        },
        {
          key: 'responsibilities',
          label: '辦理單位及人員',
          sortable: false,
          tdClass: 'align-middle',
          thStyle: { background: '#1d325f', color: '#ffffff' }
        },
        {
          key: 'processing_date',
          label: '辦理日期',
          sortable: false,
          tdClass: 'align-middle',
          thStyle: { background: '#1d325f', color: '#ffffff' }
        },
        {
          key: 'status',
          label: '辦理狀態',
          sortable: false,
          tdClass: 'align-middle',
          thStyle: { background: '#1d325f', color: '#ffffff' }
        },
        {
          key: 'many',
          label: '版次/文號/備註',
          sortable: false,
          tdClass: 'text-left',
          thStyle: { background: '#1d325f', color: '#ffffff' }
        },
        {
          key: 'fileTokens',
          label: '相關檔案',
          sortable: false,
          tdClass: 'align-middle',
          thStyle: { background: '#1d325f', color: '#ffffff' }
        }
      ],
      resultOptions: [
        { value: 'N1', text: 'N1' },
        { value: 'N2', text: 'N2' },
        { value: 'N3', text: 'N3' },
        { value: 'N4', text: 'N4' }
      ],
      fileManagement: {}
    }
  },
  async created () {
    if (this.$route.query.fid !== undefined) {
      await this.$store.dispatch(
        'newDocument/lookupDoc',
        this.$route.query.fid
      )
    }
  },
  async mounted () {
    try {
      this.staffs = await this.$store.dispatch('project/lookupStaffs', {
        selects: ['_id', 'name']
      })
      this.usePermission()
      console.log(this.fileManagement)
    } catch (err) {
      console.log(err)
    }
  },
  methods: {
    ...mapActions('newDocument', ['lookupDoc', 'initControl', 'patch']),
    ...mapMutations('newDocument', ['setNewDoc']),
    async pushTo (id) {
      this.$router.push({
        name: 'FileReviewUpload',
        query: { fid: this.$route.query.fid, relatedFile: id }
      })
    },
    async patchControlWork (index) {
      // 單筆編輯(關)
      let yes = confirm('確定儲存?')
      if (yes) {
        this.$emit('ispatch')
        this.newDocHasEdit[index].isFix = false
        this.$refs.selectableTable.refresh()
        alert('修改成功！')
        await this.patch()
      }
    },
    editControlWork (index) {
      if (this.fileManagement.permission === 1) {
        alert('無編輯權限!')
      } else {
        this.$emit('isedit')
        this.newDocHasEdit[index].isFix = true
        this.$refs.selectableTable.refresh()
      }
      // 單筆編輯(開)
      // console.log(this.newDocHasEdit)
    },
    backToControl () {
      this.$router.push({
        name: 'Deliver'
      })
    },
    async edit (id) {
      this.isfixs = true
      console.log(id)
    },
    async save (id) {
      console.log(id)
    },
    isEdit () {
      this.isFix = true
    },
    isSave () {
      this.isFix = false
    },
    getFormattedDate (date) {
      // 轉換日期格式
      let d = this.newDoc.controlWork.scheduledDate
      if (date) {
        return moment(date).format('YYYY-MM-DD')
      } else {
        return d
      }
    },
    // crying () {
    //   this.$store.commit('index/edits')
    // },
    async AssignmentModal () {
      // 新增作業按鈕
      await this.initControl()
      this.AddAssignmentModalOpen = true
    },
    async deleteControl (id) {
      // 刪除管控作業
      if (this.fileManagement.permission === 1) {
        alert('無刪除權限!')
      } else {
        if (!confirm('確定刪除此文件嗎？')) return
        await this.$store.dispatch('newDocument/deleteControlWork', id)
        alert('已刪除')
        await this.lookupDoc(this.newDoc._id)
      }
    },
    usePermission () { // 確認權限
      Object.values(this.currentUser.tenderPermissions).forEach(obj => {
        if (obj.tenderId === this.currentUser.defaultTender) {
          let permission = obj.permission
            .filter(name => name.title === '工作協同')
            .map(val => { return val.functionItem })
          for (const element of permission) {
            for (const a of element) {
              if (a.name === '文件提審') this.fileManagement = a
            }
          }
        }
      })
    }
  },
  filters: {
    ellipsis (value) {
      if (value.length > 18) {
        return value.slice(0, 14) + '...'
      }
      return value
    }
  },
  computed: {
    // isfixs () {
    //   return this.$store.state.isfixs
    // },
    ...mapGetters(['getEnumWord']),
    ...mapGetters('newDocument', ['newDocHasEdit']),
    ...mapState({
      newDoc: (state) => state.newDocument.NewDoc,
      currentUser: (state) => state.user.current
    })
  },
  watch: {
    $route (to, from) {
      this.show = false
      // console.log(from)
    },
    deep: true,
    immediate: true
  }
}
</script>

<style>
.thClass {
  background-color: #1d325f;
  color: white;
}
.table.b-table > thead > tr > th,
.table.b-table > tfoot > tr > td {
  background-image: none !important;
}
</style>
<style scoped>
/deep/ .table.b-table > thead > tr > th {
  background-color: #1d325f;
  color: white;
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  z-index: 2;
}
.form-control {
  color: black;
}
.shadow {
  background-color: #ffff;
  height: 65px;
  width: 100%;
  box-shadow: 2px 2px 20px rgba(0, 0, 0, 40);
  /* border-bottom-width:3px;
    border-bottom-color:#1D325F;
    border-bottom-style:solid */
  position: fixed;
  top: 55px;
  z-index: 500;
}
.thClass /deep/ {
  font-size: 16px;
  background-color: #1d325f;
  color: white;
}
</style>
<style lang="scss" scoped>
.btn1 {
  // 新增作業按鈕
  background-color: rgb(75, 102, 255);
  font-size: 16px;
  margin-top: 15px;
  margin-left: 15px;
  padding-left: 7px;
  padding-right: 7px;
  padding-top: 5px;
  padding-bottom: 5px;
  color: #ffffff;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.3);
  border: none;
  hover {
    color: rgb(255, 255, 255);
    background-color: rgb(49, 68, 175);
  }
}
.container {
  height: 30px;
  margin-top: 0px;
  margin-left: 5%;
  padding-top: 10px;
  padding-left: 1%;
  padding-right: 1%;
}
.text-center {
  color: #f7fafc;
  width: 100%;
  height: 100%;
  padding-left: 0px;
  padding-right: 0px;
  margin-top: 10px;
}
.b {
  // Table按鈕
  background-color: white;
  font-size: 16px;
  margin-left: 15px;
  padding-left: 7px;
  padding-right: 7px;
  padding-top: 5px;
  padding-bottom: 5px;
  color: #383838;
  border: none;
}
.b:hover {
  color: black;
  background-color: rgb(228, 228, 228);
}
</style>
