<template>
  <div class="inline-16">
    <el-button size="small" type="text" @click="onshow(drawer=true)">详情</el-button>
    <el-drawer
        title="编辑"
        :visible.sync="drawer"
        :with-header="false"
        direction="rtl"
        size="90%"
        append-to-body
        v-if="status"
        @close="onClose">
      <div class="detail__panel">
        <div class="container normal-panel sticky">
          <!--          <el-button v-show="save"  type="warning" size="small"  @click="onSubmit()" >保 存</el-button>-->
          <el-button class="inline-16" v-if="tool.checkAuth($route.name,'update')" :disabled="form.status == '发布'"  type="primary" size="small"  @click="onEdit()" >编 辑</el-button>
          <release class="inline-16" v-if="edit" :data="form" @onSuccess="onSuccess"></release>
          <Del class="inline-16" v-if="tool.checkAuth($route.name,'delete')" :data="{sat_submiteditmodelid:$route.query.id}" @onSuccess="drawer=false,$router.push('/submit_mag')"/>
<!--          <el-button class="inline-16"  type="primary" plain v-if="edit" size="mini" @click="$router.push({path:'/submit_detail',query:{id:this.id}})">明 细</el-button>-->
<!--          <p class="inline-16">编辑</p>-->
<!--          <release  class="inline-16" v-if="tool.checkAuth($route.name,'update') && edit"  :data="form" @onSuccess="onSuccess"></release>
          <topping  class="inline-16" v-if="tool.checkAuth($route.name,'update') && edit" :data="form" @onSuccess="onSuccess"></topping>-->
        </div>
        <div >
          <el-row :gutter="16">
            <el-col :span="13">
              <div class="container normal-panel normal-margin">
                <p class="normal-title normal-margin">提报设置</p>
                <el-row :gutter="16">
                  <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="right" size="small" :disabled="edit">
                    <el-col :span="24">
                      <el-form-item label="标题" prop="title">
                        <el-input v-model="form.title" placeholder="标题"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="提报类型" prop="onceonly">
                        <el-select v-model="form.onceonly" placeholder="选择提报类型">
                          <el-option label="一事一报" :value="1"></el-option>
                          <el-option label="一事多报" :value="0"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="生效日期" prop="begdate">
                        <el-date-picker style="width:100%" v-model="form.begdate" value-format="yyyy-MM-dd" type="date"
                                        placeholder="生效日期">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="截止日期" prop="enddate">
                        <el-date-picker style="width:100%" v-model="form.enddate" value-format="yyyy-MM-dd" type="date"
                                        placeholder="截止日期">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="提报要求" prop="notes">
                        <el-input v-model="form.notes" placeholder="提报要求"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="提报形式" prop="type">
                        <el-checkbox-group v-model="form.type" @change="onCheckboxChange">
                          <el-checkbox label="附件提报" name="isattrequired"></el-checkbox>
                          <el-checkbox label="文字提报" name="istextrequired"></el-checkbox>
                        </el-checkbox-group>
                      </el-form-item>
                    </el-col>
                  </el-form>
                </el-row>
              </div>
              <div class="container normal-panel normal-margin">
                <attachmentList :attinfos="form.attinfos" @onSuccess="querySubmitMain" :onlyread="store.state.pageOnlyRead">
                  <upload slot="upload" :folderid="folderid"
                          :bindData="{ ownertable: 'sat_submiteditmodel', ownerid: form.sat_submiteditmodelid, usetype: 'default' }"
                          @onSuccess="onSubmit()"></upload>
                </attachmentList>
              </div>
            </el-col>
            <el-col :span="11" :onlyread="store.state.pageOnlyRead">
              <scopeOfauth v-if="defaultData" :defaultData="defaultData" :disabled="!save" appidname="sat_submiteditmodelid" obiectName="sat_submiteditmodel" :dataid="$route.query.id"
                           @onChecked="onChecked"></scopeOfauth>
            </el-col>
          </el-row>
        </div>

      </div>
      <div class="fixed__btn__panel" v-show="save">
        <el-button  size="small" @click="onCancel" class="normal-btn-width">取 消</el-button>
        <el-button  size="small" type="primary" @click="onSubmit" class="normal-btn-width">确 定</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import attachmentList from '@/components/attachment_list/index.vue'
import upload from '@/components/upload/hw_obs_upload.vue'
import scopeOfauth from '@/components/scopeOfAuthority/index.vue'
import store from '@/store'
import release from './release'
import Del from './delete'
export default {
  props:["id"],
  components: {
    attachmentList,
    upload,
    scopeOfauth,
    release,
    Del
  },
  data() {
    var checkTime = (rule, value, callback) => {
      if (this.form.enddate) {
        if (new Date(value).getTime() > new Date(this.form.enddate).getTime()) {
          callback(new Error('生效日期不能大于截止日期'));
        } else {
          callback()
        }
      }     
    };
    var checkTime2 = (rule, value, callback) => {
      if (this.form.begdate) {
        if (new Date(value).getTime() < new Date(this.form.begdate).getTime()) {
          callback(new Error('截止日期不能小于生效日期'));
        } else {
          callback()
        }
      }     
    };
    var endDate = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('截止日期不可为空'));
          } else {
            if (value !== '') {
              if (this.form.begdate > this.form.enddate)
                callback(new Error('截止日期不可小于生效日期'));
            }
            callback();
          }
        }
    return {
      authData: {
        departmentid: [],
        hrid: [],
        isonlymanager_agent: false,
        isonlymanager_dept: false,
        sa_agentsid: [],
        sat_submiteditmodelid: '',
      },
      store,
      drawer:false,
      edit:true,
      save:false,
      status:false,
      folderid: JSON.parse(sessionStorage.getItem('folderid')).appfolderid,
      defaultData: '',
      rules: {
        title: [
          { required: true, message: '请输入课程名称', trigger: 'blur' },
        ],
        begdate: [
          { required: true, message: '请选择生效日期', trigger: 'change' },
          { required: true, validator: checkTime, trigger: 'change' },
        ],
        enddate: [
          { required: true,validator: endDate, trigger: 'blur'  },
          { required: true, validator: checkTime2, trigger: 'change' },
        ],
        onceonly: [
          { required: true, message: '请选择版块', trigger: 'change' }
        ],
        type: [
          { type: 'array', required: true, message: '请至少选择一个提报形式', trigger: 'change' }
        ],
      },
      form: {
        "title": "",
        "notes": "",
        "istextrequired": 1,
        "isattrequired": 1,
        "onceonly": 1,
        "sat_submiteditmodelid": "0",
        "begdate": "",
        "enddate": "",
        "type": []
      },
    }
  },
  watch: {
    drawer (val) {
      if(!val) {
        this.save =false
        this.edit = true
      }
    },
    edit (val) {
      if(val) {
        this.$store.dispatch('pageOnlyRead',true)
      } else {
        this.$store.dispatch('pageOnlyRead',false)
      }
    }
  },
  methods: {
    async querySubmitMain() {
      const res = await this.$api.requested({
        "id":"20221102093902",
        "content": {
          "sat_submiteditmodelid": this.id
        }
      })
      console.log("获取数据")
      console.log(res)
      res.data.notes == '初始化数据' + JSON.parse(sessionStorage.getItem('active_account')).userid ? res.data.notes = '' : '';
      this.form = Object.assign({}, this.form, res.data)
      if (this.form.isattrequired === 1) { this.form.type.push('附件提报') }
      if (this.form.istextrequired === 1) { this.form.type.push('文字提报') }

      this.form.status !== '新建' ? store.state.pageOnlyRead = true : store.state.pageOnlyRead = false

      if(!this.save) {
        this.$store.dispatch('pageOnlyRead',true)
      } else {
        this.$store.dispatch('pageOnlyRead',false)
      }

      this.status = true
    },
    onSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (!valid) return false;
        const res = await this.$api.requested({
          "id":20221102093702,
          "content": this.form
        })
        this.edit = true
        this.insertCoursewareauth(res.data)
        this.drawer = false
        this.$emit("updateSuccess")
      })
    },
    // 监听提报形式
    onCheckboxChange(val) {
      this.form.isattrequired = val.indexOf('附件提报') === -1 ? 0 : 1
      this.form.istextrequired = val.indexOf('文字提报') === -1 ? 0 : 1
    },
    // 获取保存授权范围数据
    onChecked(param) {
      this.authData = param
      console.log(this.authData)
    },
    // 新增授权范围
    async insertCoursewareauth(data) {
      this.authData.sat_submiteditmodelid = data.sat_submiteditmodelid
      if (this.authData.departmentid.length == 0) this.authData.departmentid = this.defaultData.departmentid
      if (this.authData.hrid.length == 0) this.authData.hrid = this.defaultData.hrid
      if (this.authData.sa_agentsid.length == 0) this.authData.sa_agentsid = this.defaultData.sa_agentsid
      if (this.authData.sa_saleareaid.length == 0) this.authData.sa_saleareaid = this.defaultData.sa_saleareaid.departmentid
      const res = await this.$api.requested({
        "id":"20221102094302",
        "content": this.authData
      })
      res.code === 0 ? this.$notify({
        title: '失败',
        message: res.data,
        type: 'error'
      }) : this.querySubmitMain()

    },
    // 查询授权信息
    async query_auth() {
      const res = await this.$api.requested({
        "id":'20221102094602',
        "content": {
          "sat_submiteditmodelid": this.$route.query.id,
        }
      })
      this.defaultData = res.data
      console.log(this.defaultData);
      
    },
    onshow(){
      this.$router.replace({path:'submit_mag',query:{id:this.id}})
      this.querySubmitMain()
      this.query_auth()
    },
    onClose(){
      this.drawer = false
      this.$emit("updateSuccess")
    },
    onEdit(){
      this.edit = false
      this.save = true
    },
    onSuccess(){
      this.drawer = false
      this.querySubmitMain()
    },
    onCancel(){
      this.edit = true
      this.save = false
    }

  },
  created() {
    this.status = false
  },
}

</script>
<style>
</style>