<template>
  <div class="edit-add-detail">
    <div class="form-content">
      <el-form
        ref="addEditForm"
        :model="addEditForm"
        :rules="addEditRules"
        class="edit-add-form"
        label-position="left"
        label-width="140px"
      >
        <div class="rows">
          <div class="rows-left">
            <div class="rows-hr"></div>
          </div>
          <div class="rows-title">
            <div class="text-overflow">{{ paibanday }}排班信息</div>
          </div>
        </div>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="队伍名称" prop="orgId">
              <el-select
                style="width: 100%"
                disabled
                v-model="addEditForm.orgId"
                filterable
                placeholder="请选择队伍"
              >
                <el-option
                  v-for="item in orgOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="班种" prop="rankId">
              <el-select
                v-model="addEditForm.rankId"
                filterable
                placeholder="请选择班种"
                @change="changeRank"
              >
                <el-option
                  v-for="item in rankData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="负责人" prop="responsId">
              <el-select
                v-model="addEditForm.responsId"
                filterable
                placeholder="请选择负责人"
                @change="(value) => changeUser(value, 'responsName')"
              >
                <el-option
                  v-for="item in worker"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="12">
            <el-form-item label="排班人员" prop="userId">
              <el-select
                v-model="addEditForm.userId"
                multiple
                filterable
                placeholder="请选择人员"
                @change="(value) => changeUser(value, 'userName')"
              >
                <el-option
                  v-for="item in worker"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="18">
            <el-form-item label="日期" prop="rankDate">
              <el-select
                v-model="addEditForm.rankDate"
                :disabled="!istongbuchoose"
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) in dates"
                  :key="index"
                  :disabled="item.day == paibanday"
                  :label="item.day"
                  :value="item.day"
                >
                  <span style="float: left">{{ item.day }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.week
                  }}</span>
                </el-option>
              </el-select>
              <el-checkbox
                v-model="istongbuchoose"
                class="tongbuchoose"
                @change="getTongbu"
              >
                同步排班
              </el-checkbox>
              &nbsp;&nbsp;
              <el-tooltip
                class="item"
                effect="dark"
                content="选中日期将同步应用当前配置的排班信息"
                placement="bottom"
              >
                <i class="el-icon-info icon-info"></i>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="footer">
      <el-button :loading="saveLoading" type="primary" @click="handleSave">
        {{ $t('domestic.save') }}
      </el-button>
      <el-button @click="changePage('CalenderPage')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import {
  orgTree,
} from '@/api/patrolAndRescue/roadWatch/inspectScheduling/inspectWorkGroupContent'

import {
  getUsersByOrg,
  saveArrangeInfo,
  getArrangeInfoDetail,
} from '@/api/patrolAndRescue/roadWatch/inspectScheduling/inspectWorkUserContent'
import {getDictionaryByCode} from '@/utils/dictionary'

export default {
  name: 'EditAddPage',
  components: {},
  props: {
    componentName: {
      default: 'EditAddPage',
      type: String,
    },
  },
  data() {
    return {
      id: '', // id标识符
      paibanday: '', // 排班日期
      addEditForm: {
        orgId: '',
        rankId: '',
        userId: [],
      },
      addEditRules: {
        rankId: {
          required: true,
          message: '请选择班种',
          trigger: 'blur',
        },
        userId: {
          required: true,
          message: '请至少选择一名人员',
          trigger: 'blur',
        },
        responsId: {
          required: true,
          message: '请选择负责人',
          trigger: 'blur',
        },
        rankDate: {
          required: true,
          message: '请至少选择一天',
          trigger: 'blur',
        },
      },
      saveLoading: false,
      pubSub: null,
      worker: [],
      orgOptions: [],
      rankData: [],
      dates: [],
      istongbuchoose: false,
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      },
    },
  },
  created() {},
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      this.getOrgData()
      this.paibanday = data.day.day
      let month = parseInt(this.paibanday.slice(5, 7))
      let year = parseInt(this.paibanday.slice(0, 4))
      this.getDates(year, month)
      this.rankData = data.rankData || []

      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      } else {
        this.addEditForm = {
          orgId: data.orgId,
          rankId: data.rankId,
          rankDate: [data.day.day],
        }
        if(data.rankId){
          this.addEditForm.rankName =
            this.rankData.find((item) => item.id === data.rankId)?.name || ''
        }
      }
      this.getOrgUsersList(data.orgId)
    })
  },
  methods: {
    getDictionaryByCode,
    changeUser(value, type) {
      if (type == 'userName') {
        this.addEditForm[type] = []
        for (let i = 0; i < this.worker.length; i++) {
          for (let j = 0; j < value.length; j++) {
            if (this.worker[i].id == value[j]) {
              this.addEditForm[type].push(this.worker[i].name)
            }
          }
        }
      } else {
        this.addEditForm[type] = ''
        for (let i = 0; i < this.worker.length; i++) {
          if (this.worker[i].id == value) {
            this.addEditForm[type] = this.worker[i].name
          }
        }
      }
    },
    changeRank(value) {
      this.addEditForm.rankName =
        this.rankData.find((item) => item.id === value)?.name || ''
    },
    getOrgUsersList(orgId) {
      const query = {
        pageBean: {
          page: 1,
          pageSize: -1,
        },
        querys: [
          {
            group: 'main',
            operation: 'IN',
            parentGroup: '',
            property: 'bm.team_id_',
            relation: 'AND',
            value: orgId,
          },
        ],
      }
      getUsersByOrg(query).then((res) => {
        console.log(res)
        this.worker = res.rows || []
      })
    },
    // 获取所在监控中心列表数据
    async getOrgData() {
      try {
        let {value} = await orgTree() // 调用 API 获取树形数据
        this.orgOptions = value
        this.orgOptions = this.orgOptions.reduce((accumulator, item) => {
          return accumulator.concat(item.teamList);
        }, []);
      } finally {
      }
    },
    // 获取当前月的日期
    getDates(year, month) {
      this.dates = []
      var currentMonthDays = new Date(year, month, 0).getDate()
      let weekList = [
        '星期日',
        '星期一',
        '星期二',
        '星期三',
        '星期四',
        '星期五',
        '星期六',
      ]
      var startDate = new Date(year, month - 1, 1)

      for (let day = 1; day <= currentMonthDays; day++) {
        // 截至当前日期为止
        // 年月日(yyyy-MM-dd)

        this.dates.push({
          day:
            year +
            '-' +
            (month < 10 ? '0' + month : month) +
            '-' +
            (day < 10 ? '0' + day : day),
          week: weekList[new Date(startDate.setDate(day)).getDay()],
        })
      }
    },
    getTongbu() {
      if (this.istongbuchoose == false) {
        this.dialogForm.rankDate.length = 0
        this.dialogForm.rankDate.push(this.paibanday)
      }
    },
    // 打开页面执行
    openPage() {},
    // 关闭页面执行
    closePage() {
      const {roadOptions} = this
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub: this.pubSub,
        roadOptions,
      })
      this.$nextTick((_) => {
        this.$refs.addEditForm.$el.scrollTop = 0
        this.$refs.addEditForm.clearValidate()
      })
    },
    // 获取详情
    async getDetail(id) {
      const {
        userName = '',
        userId = '',
        rankDate = '',
        ...rest
      } = await getArrangeInfoDetail(id)
      this.addEditForm = {
        userId: userId.split(','),
        userName: userName.split(','),
        rankDate: rankDate.split(','),
        ...rest,
      }
    },
    // 保存
    handleSave() {
      this.$refs.addEditForm.validate(async (valid, object) => {
        if (!valid) {
          this.$message.warning(
            `有${
              Object.keys(object).length
            }个字段未通过校验，请正确填写表单内容。`
          )
        } else {
          this.saveLoading = true
          let data = JSON.parse(JSON.stringify(this.addEditForm))
          const {rankDate = [], userId = [], userName = [], ...rest} = data
          const querys = rankDate.map((item) => {
            return {
              rankDate: item,
              userId: userId.join(','),
              userName: userName.join(','),
              ...rest,
            }
          })
          console.log(querys)
          try {
            const response = await saveArrangeInfo(querys)
            const {state, message} = response
            if (state) {
              const action = this.id ? '编辑' : '新增'
              this.$message.success(`${action}成功`)
              PubSub.publish('CalenderPage', {type: this.id ? 'edit' : 'add'})
              this.changePage('CalenderPage', this.id ? 'edit' : 'add')
            } else {
              this.$message.error(message)
            }
          } finally {
            this.saveLoading = false
          }
        }
      })
    },
    // 改变页面
    changePage(pageName = '', type = '') {
      if (!pageName) return
      this.$emit('changePage', pageName, (_) => {
        PubSub.publish(pageName, {type})
      })
    },
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  },
}
</script>

<style lang="scss" scoped>

.icon-info{
    font-size: 14px;
    color: #e6a23c;
}
</style>
