<template>
  <a-modal
    v-model="visible"
    :title="title"
    width="100%"
    :class="$style.modal"
    destroy-on-close
    :mask-closable="false"
    @ok="save"
    @cancel="visible = false"
  >
    <div :class="$style.warp">
      <div :class="$style.header">
        <span :class="$style['year-switch']">
          <a-icon type="caret-left" @click="changeYear('pre')" />
          {{ year }} 年
          <a-icon type="caret-right" @click="changeYear('next')" />
        </span>
        <sd-form ref="form" :init-values="values" :class="$style['input-warp']">
          <template v-slot="{ model }">
            <table :class="$style.form">
              <tr>
                <sd-form-item-td
                  :class="$style.item"
                  name="calendarCode"
                  :input-props="{
                    disabled: unid && unid !== '' ? true : false,
                  }"
                ></sd-form-item-td>

                <sd-form-item-td :class="$style.item" name="calendarName"></sd-form-item-td>

                <sd-form-item-td :class="$style.item" name="orgCode">
                  <template v-slot>
                    <sd-value-picker
                      v-model="model.orgCode"
                      single
                      option-value="key"
                      option-label="title"
                      :class="$style.orgCode"
                    >
                      <template v-slot="scope">
                        <sd-picker-source-tree :load-tree-data="onLoadTreeData" v-bind="scope" />
                      </template>
                    </sd-value-picker>
                  </template>
                </sd-form-item-td>
              </tr>
            </table>
          </template>
        </sd-form>
        <span :class="$style['warp-btn']">
          <a-button @click="showWorkTime">工作时间</a-button>
          <a-button @click="resetCalendar">恢复默认日历</a-button>
        </span>
      </div>
      <div :class="$style.content">
        <!-- <a-space> -->
        <div :class="$style.illustration">
          <a-radio-group v-model="switchMode">
            <a-radio :value="0">
              <i :class="$style.legendIcon"></i><span :class="$style.legendLabel">工作日</span>
            </a-radio>
            <a-radio :value="1" :class="$style.weekend">
              <i :class="$style.legendIcon"></i><span :class="$style.legendLabel">休息日</span>
            </a-radio>
          </a-radio-group>
          <span :class="$style.note">提示：点击日历可设置日期的类型，类型可勾选图例切换。</span>
        </div>
        <div v-for="(month, index) in 12" :key="year + '-' + index" :class="$style.calender">
          <a-calendar
            :fullscreen="false"
            mode="month"
            :header-render="headerRender"
            :default-value="getDefaultDate(month)"
            :month="month"
          >
            <template slot="dateFullCellRender" slot-scope="value">
              <template v-if="value.month() + 1 === month">
                <div :class="$style[getClass(value)]" @click="changeDayType(value)">
                  {{ value.format('D') }}
                </div>
              </template>
            </template>
          </a-calendar>
        </div>
        <!-- </a-space> -->
      </div>
    </div>
    <sd-worktime ref="workTime" @updateTimeCode="updateTimeCode"></sd-worktime>
  </a-modal>
</template>

<script>
import { message } from 'ant-design-vue'
import moment from 'moment'
import OrgService from '../org-manager/org-service'
import components from './_import-components/sd-workday-import'
import WorkdayService from './workday-service'

export default {
  name: 'SdWorkday',
  metaInfo: {
    title: 'SdWorkday',
  },
  components: { ...components },
  data() {
    return {
      visible: false,
      unid: null,
      title: '',
      year: null,
      updateKey: 0,
      isReady: false,
      calendarCode: '',
      calendarName: '',
      orgInfo: [],
      moment,
      curYearDayStatus: [],
      includeYears: [],
      values: [
        {
          name: 'calendarCode',
          caption: '编码',
          required: true,
          dataType: 'string',
        },
        {
          name: 'calendarName',
          caption: '名称',
          required: true,
          dataType: 'string',
        },
        {
          name: 'orgCode',
          caption: '所属机构',
          required: true,
          dataType: 'string',
        },
      ],
      switchMode: 0,
      curTimeCode: '',
    }
  },
  computed: {
    workhours: function() {
      return ''
    },
  },
  methods: {
    changeYear(sType) {
      if (!this.unid) {
        message.error('请保存工作日历后再切换年份!')
        return
      }
      if (sType === 'pre') {
        this.year--
      } else {
        this.year++
      }
      if (this.unid) {
        if (this.includeYears.indexOf(this.year) === -1) {
          this.initTheYear(this.year).then((_) => {
            this.updateKey++
          })
        } else {
          this.getDefualtValue(this.unid, this.year).then((_) => {
            this.updateKey++
          })
        }
      }
    },
    clear() {
      this.calendarCode = ''
      this.calendarName = ''
      this.curYearDayStatus = []
      this.includeYears = []
      this.orgInfo = []
      this.curTimeCode = ''
    },
    show(title, unid, year) {
      this.clear()
      this.switchMode = 0
      this.title = title
      this.unid = unid
      if (unid) {
        this.year = parseInt(year, 10)
        this.getDefualtValue(this.unid, this.year)
      } else {
        this.initCalendar()
      }
      this.visible = true
    },
    getDefaultDate(month) {
      return moment(this.year + '-' + month + '-01')
    },

    initTheYear(year) {
      return new Promise((resolve) => {
        this.loadingMsg = message.loading({
          key: this.msgKey,
          content: '处理中...',
          duration: 0,
        })
        WorkdayService.initWorkDay({
          calendarCode: this.calendarCode,
          year,
        })
          .then((res) => {
            if (res.status === 200) {
              const data = res.data
              this.curYearDayStatus = data.items
              this.includeYears = data.includeYears.split(',').map((item) => {
                return parseInt(item, 10)
              })

              message.success('处理成功')
            } else {
              message.error(res.data?.message || '处理失败')
            }
          })
          .catch(() => message.error('处理失败'))
          .finally(() => {
            this.loadingMsg?.()
          })
      })
    },
    headerRender({ value, type, onChange, onTypeChange }) {
      return (
        <div style='text-align:center'>
          <span>{value.format('MMMM')}</span>
        </div>
      )
    },
    getDefualtValue(unid, year) {
      return new Promise((resolve) => {
        this.loadingMsg = message.loading({
          key: this.msgKey,
          content: '处理中...',
          duration: 0,
        })
        WorkdayService.getDoc({
          id: unid,
          itemsYear: year,
        })
          .then((res) => {
            if (res.status === 200) {
              const data = res.data

              this.calendarCode = data.calendarCode
              this.calendarName = data.calendarName
              this.orgInfo = [{ key: data.orgCode, title: data.orgName }]

              const thisForm = this.$refs.form
              if (thisForm)
                this.values.forEach((item) => {
                  if (item.name !== 'orgCode') {
                    thisForm.setFieldValue(item.name, data[item.name])
                  } else {
                    thisForm.setFieldValue(item.name, [
                      { key: data.orgCode.split('G')[1], title: data.orgName },
                    ])
                  }
                })
              this.curTimeCode = data.calendarCode + '_workday'
              this.curYearDayStatus = data.items
              this.includeYears = data.includeYears.split(',').map((item) => {
                return parseInt(item, 10)
              })
            } else {
              message.error(res.data?.message || '处理失败')
            }
          })
          .catch(() => message.error('处理失败'))
          .finally(() => {
            this.loadingMsg?.()
          })
      })
    },
    getClass(value) {
      const dayIndex = value.format('DDD')
      if (this.curYearDayStatus[dayIndex - 1]) {
        return this.curYearDayStatus[dayIndex - 1].timeCode === '_sys_weekend'
          ? 'freeday'
          : 'workday'
      } else {
        if (['5', '6'].indexOf(value.format('e')) > -1) {
          return 'freeday'
        } else {
          return 'workday'
        }
      }
    },
    showWorkTime() {
      if (
        this.$refs.form.getFieldValue('calendarCode') &&
        this.$refs.form.getFieldValue('calendarCode') !== ''
      ) {
        this.$refs.workTime.show('工作时间', this.$refs.form.getFieldValue('calendarCode'))
      } else {
        message.warn('请输入日历编码')
      }
    },
    changeDayType(value) {
      const curTimeCode = this.curTimeCode || '_sys_workday'
      const dayIndex = value.format('DDD')
      this.curYearDayStatus[dayIndex - 1].timeCode =
        this.curYearDayStatus[dayIndex - 1].timeCode === '_sys_weekend'
          ? curTimeCode
          : this.switchMode === 1
          ? '_sys_weekend'
          : curTimeCode
    },
    save() {
      return new Promise((resolve) => {
        this.$refs.form.validateFields().then((success) => {
          if (success) {
            this.loadingMsg = message.loading({
              key: this.msgKey,
              content: '处理中...',
              duration: 0,
            })

            const calendarCode = this.$refs.form.getFieldValue('calendarCode')
            const orgCode = this.$refs.form.getFieldValue('orgCode')[0]?.key
            WorkdayService.saveDoc({
              data: {
                year: this.year,
                id: this.unid ? parseInt(this.unid, 10) : 0,
                calendarCode: this.$refs.form.getFieldValue('calendarCode'),
                calendarName: this.$refs.form.getFieldValue('calendarName'),
                orgCode: orgCode.indexOf('G') === -1 ? 'G' + orgCode : orgCode,
                orgName: this.$refs.form.getFieldValue('orgCode')[0].title,
                items: this.curYearDayStatus.map((item) => {
                  item.calendarCode = calendarCode
                  return item
                }),
              },
            })
              .then((res) => {
                if (res.status === 200) {
                  this.unid = res.data.id
                  this.visible = false
                  message.success('处理成功')
                  this.$emit('feedback', true)
                } else {
                  message.error(res.data?.message || '处理失败')
                }
              })
              .catch((error) => {
                message.error({
                  key: this.msgkey,
                  content: error.response?.data?.message || '处理失败',
                })
              })
              .finally(() => {
                this.loadingMsg?.()
                resolve()
              })
          }
        })
      })
    },

    onLoadTreeData(parentCatId, parentCatObj) {
      return new Promise((resolve) => {
        if (parentCatId) {
          return OrgService.getOrgDepTree({ id: parentCatId }).then((deps) => {
            resolve(this.parseTreeData(deps.data))
          })
        } else {
          return OrgService.getOrgDepRoot().then((roots) => {
            resolve(this.parseTreeData(roots.data))
          })
        }
      })
    },
    parseTreeData(deps) {
      return deps.map((dep) => {
        return {
          key: dep.id,
          title: dep?.props?.hierarchical === 'true' ? dep.text + '(已开启分级)' : dep.text,
          name: dep.text,
          isLeaf: dep.leaf,
          scopedSlots: {
            title: 'title',
          },
          originalNode: {
            ...dep,
          },
        }
      })
    },
    initCalendar() {
      this.year = moment().year()
      this.includeYears = [this.year]
      this.curYearDayStatus = []

      const momentDay = moment(this.year + '-01-01')

      for (let i = 0; i < 367; i++) {
        if (i !== 0) {
          momentDay.add(1, 'days')
        }
        if (momentDay.year() !== this.year) {
          break
        }
        if (!this.curYearDayStatus[i]) {
          this.curYearDayStatus[i] = {
            calendarCode: this.calendarCode,
            timeCode:
              ['5', '6'].indexOf(momentDay.format('e')) > -1
                ? '_sys_weekend'
                : (this.calendarCode || '_sys') + '_workday',
            year: momentDay.year(),
            month: momentDay.month(),
            day: momentDay.date(),
            color: null,
            dateStr: momentDay.format('YYYYMMDD'),
            dateMillis: 0,
          }
        }
      }
    },
    resetCalendar() {
      this.initCalendar()
    },
    updateTimeCode(data) {
      this.curTimeCode = data.timeCode
      this.curYearDayStatus = this.curYearDayStatus.map((item) => {
        // 将工作日的timeCode默认值替换成新的(_workday是错误数据，兼容26版本新建的工作日历)
        if (['_sys_workday', '_workday'].includes(item.timeCode)) {
          item.timeCode = this.curTimeCode
        }
        return item
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.warp {
  .calender {
    display: inline-block;
  }
}
.modal {
  /* stylelint-disable-next-line  */
  // height: 100% !important;
  // :global(.ant-modal-wrap) {
  //   /* stylelint-disable-next-line  */
  //   height: 100% !important;
  // }
  .workday {
    text-align: center;
  }
  .freeday {
    text-align: center;
    background: rgb(26, 188, 156);
    /* stylelint-disable-next-line  */
    color: rgb(255, 255, 255);
  }
  .year-switch {
    display: inline-block;
    padding: 10px 0 0 0;
    vertical-align: top;
  }

  .input-warp {
    display: inline-block;
  }
  .item {
    width: 30%;
  }
  .warp-btn {
    display: inline-block;
    padding: 7px 0 0 0;
    vertical-align: top;
    button:first-child {
      margin: 0 12px;
    }
  }
  .calender {
    width: 24%;
    padding: 0 5px;
    margin: 4px;
    border: 1px solid #ccc;
  }
  .calender-header {
    font-size: $btn-font-weight;
    text-align: center;
  }
}
.illustration {
  margin-bottom: 12px;
  .legend-icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin: 2px;
    vertical-align: middle;
    border: 1px solid rgb(204, 204, 204);
  }
  .legend-label {
    vertical-align: middle;
    /* stylelint-disable-next-line  */
    color: rgb(153, 153, 153);
  }
  .weekend {
    .legend-icon {
      /* stylelint-disable-next-line  */
      background-color: #1abc9c;
    }
  }
  .note {
    /* stylelint-disable-next-line  */
    color: rgb(51, 51, 51);
  }
}
.form {
  :global(.ant-form-item-label) {
    width: 120px;
  }
  :global(.ant-form-item-control-wrapper) {
    width: 220px;
  }
}
.org-code {
  :global(.ant-select-search) {
    display: none;
  }
}
</style>
