<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">班组信息</div>
          </div>
        </div>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="队伍名称" prop="orgId">
              <el-select
                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="name">
              <el-input
                v-model="addEditForm.name"
                placeholder="请输入班种"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item label="上班时间" prop="workStartTime">
              <el-time-select
                v-model="addEditForm.workStartTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00',
                }"
                placeholder="上班时间"
                value-format="HH:mm"
              >
              </el-time-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="workEndTime">
              <el-time-select
                v-model="addEditForm.workEndTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00',
                }"
                placeholder="下班时间"
                value-format="HH:mm"
              >
              </el-time-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="restStartTime">
              <el-time-select
                v-model="addEditForm.restStartTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00',
                }"
                placeholder="休息开始时间"
                value-format="HH:mm"
              >
              </el-time-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="restEndTime">
              <el-time-select
                v-model="addEditForm.restEndTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:15',
                  end: '24:00',
                }"
                placeholder="休息开始时间"
                value-format="HH:mm"
              >
              </el-time-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-left: 80px">
          <el-col :span="8">
            <el-form-item
              class="color-form-item"
              label="显示颜色"
              prop="markColor"
            >
              <el-color-picker
                v-model="addEditForm.markColor"
              ></el-color-picker>
              <!-- <el-radio-group v-model="addEditForm.markColor">
                <el-radio label="#F7A165"
                  ><span class="one">备选项</span></el-radio
                >
                <el-radio label="#FF8987"
                  ><span class="two">备选项</span></el-radio
                >
                <el-radio label="#4CA6FF"
                  ><span class="three">备选项</span></el-radio
                >
                <el-radio label="#37E6E6"
                  ><span class="four">备选项</span></el-radio
                >
              </el-radio-group> -->
            </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('TablePage')">
        {{ $t('domestic.cancel') }}
      </el-button>
    </div>
  </div>
</template>

<script>
import PubSub from 'pubsub-js'
import {
  tableAdd,
  tableEdit,
  orgTree,
  tableDetail,
} from '@/api/patrolAndRescue/roadWatch/inspectScheduling/inspectWorkGroupContent'
import {getDictionaryByCode} from '@/utils/dictionary'

export default {
  name: 'EditAddPage',
  components: {},
  props: {
    componentName: {
      default: 'TablePage',
      type: String,
    },
  },
  data() {
    return {
      id: '', // id标识符
      addEditForm: {
        orgId: '',
        markColor: '#4CA6FF',
      },
      addEditRules: {
        name: {
          required: true,
          message: '请输入班种',
          trigger: 'blur',
        },
        restEndTime: {
          required: true,
          message: '请选择休息结束时间',
          trigger: 'blur',
        },
        restStartTime: {
          required: true,
          message: '请选择休息开始时间',
          trigger: 'blur',
        },
        workEndTime: {
          required: true,
          message: '请选择下班时间',
          trigger: 'blur',
        },
        workStartTime: {
          required: true,
          message: '请选择上班时间',
          trigger: 'blur',
        },
        orgId: {
          required: true,
          message: '请选择监控中心',
          trigger: 'blur',
        },
      },
      saveLoading: false,
      pubSub: null,
      orgOptions: [],
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      },
    },
  },
  created() {},
  mounted() {
    this.pubSub = PubSub.subscribe('EditAddPage', (_, data) => {
      this.getOrgData()
      if (data.id) {
        this.id = data.id
        this.getDetail(data.id)
      } else {
        this.addEditForm = {
          orgId: data.orgId,
        }
      }
    })
  },
  methods: {
    getDictionaryByCode,
    // 获取所在监控中心列表数据
    async getOrgData() {
      try {
        this.treeLoading = true
        let {value} = await orgTree() // 调用 API 获取树形数据
        this.orgOptions = value
        this.orgOptions = this.orgOptions.reduce((accumulator, item) => {
          return accumulator.concat(item.teamList);
        }, []);
        this.orgId = this.orgOptions?.[0]?.id || '' // 默认选择第一个监控中心
      } finally {
        this.treeLoading = false // 无论成功或失败，都关闭加载状态
      }
    },
    // 打开页面执行
    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) {
      this.addEditForm = await tableDetail(id)
    },
    // 保存
    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 myInterFace = this.id ? tableEdit : tableAdd
          try {
            const response = await myInterFace({...this.addEditForm})
            const {state, message} = response
            if (state) {
              const action = this.id ? '编辑' : '新增'
              this.$message.success(`${action}成功`)
              PubSub.publish('TablePage', {type: this.id ? 'edit' : 'add'})
              this.changePage('TablePage', this.id ? 'edit' : 'add')
            }
          } 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>
@import "@/assets/css/element-variables";

::v-deep .el-textarea .el-input__count {
  background: transparent;
}

.stake-mark {
  ::v-deep .el-form-item__content {
    display: flex;
    justify-content: space-between;
  }
}
::v-deep .el-radio__label {
  margin-left: 10px;

  .one {
    background: #F7A165 !important;
    color: transparent!important;
  }

  .two {
    background: #FF8987 !important;
    color: transparent!important;
  }

  .three {
    background: #4CA6FF !important;
    color: transparent!important;
  }

  .four {
    background: #37E6E6 !important;
    color: transparent!important;
  }
}
</style>
