<template>
  <div class="inline-16">
    <el-button :disabled="data.status === '结束' " type="text" size="small" @click="onShow(dialogFormVisible = true)">编 辑</el-button>
    <el-dialog title="编辑模板" append-to-body :visible.sync="dialogFormVisible" width="800px">
      <el-row :gutter="20">
        <el-form :model="form" ref="form" :rules="rules" label-position="left" label-width="80px" size="small">
          <el-col :span="24">
            <el-form-item label="标题" prop="title">
              <el-input type="text" v-model="form.title" placeholder="输入提报标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="开始日期" prop="begdate">
            <el-date-picker
              style="width:100%"
              v-model="form.begdate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="enddate">
              <el-date-picker
                style="width:100%"
                v-model="form.enddate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="提醒时间" prop="taskdays">
              <div class="flex-align-center"><span style="width:40px">提 前:</span><el-input type="number" style="width:200px" v-model="form.taskdays" placeholder="输入提醒时间"></el-input>&emsp;<span>天</span></div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <div class="flex-align-center my-error-panel">
              <el-form-item label="提报周期" prop="periodtype">
                <el-select style="width:120px" v-model="form.periodtype" placeholder="请选择提报周期" @change="handleChange">
                  <el-option label="每周" value="周"></el-option>
                  <el-option label="每月" value="月"></el-option>
                  <el-option label="仅一次" value="once"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label-width="0px" prop="periodpoint">
                <el-popover
                  v-if="form.periodtype !== 'once'"
                  placement="bottom"
                  width="400"
                  trigger="click">
                  <div :class="error?'error':''" class="periodTags" slot="reference">
                    <p v-if="form.periodpoint.length === 0">请选择</p>
                    <div v-else>
                      <el-tag v-for="item in form.periodpoint" type="info" size="mini" :key="item.index" style="margin-right:5px" @close="closeDate(item)" closable>
                        {{form.periodtype === '周'?'周'+ `${item===7?'日':item}`:item+'日'}}
                      </el-tag>
                    </div>
                  </div>
                  <el-row>
                    <el-col :class="act === item?'act':''" @click.native="clickdate(item)" style="height:50px;line-height:50px;text-align:center;cursor: pointer;"  v-for="item in period" :key="item" :span="form.periodtype==='月'?4:8">{{form.periodtype === '周'?'周'+ `${item===7?'日':item}`:item+'日'}}</el-col>
                  </el-row>
                </el-popover>
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="24">
            <el-form-item label="提报要求">
              <el-checkbox v-model="form.baseonproject" :true-label="1" :false-label="0">按项目及产品类别预测</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="form.remarks" placeholder="请输入备注" :rows="3"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="发布范围" prop="roles">
              <el-select style="width:100%" v-model="form.roles" placeholder="请选择角色" @remove-tag="removeTag" multiple>
                <el-option v-for="item in rolelist" :key="item.index" :label="item.rolename" :value="item.roleid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false" class="normal-btn-width">取 消</el-button>
        <el-button size="small" type="primary" @click="onSubmit" class="normal-btn-width">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props:['data'],
  data () {    
    return {
      error:false,
      dialogFormVisible:false,
      form:{
        sa_salesforecastmodelid:0,
        title:'',
        remarks:'',
        begdate:'',
        enddate:'',
        periodtype:'周',
        periodpoint:[],
        baseonproject:false,
        isrepeat:true,
        taskdays:0,
        sales:[],
        roles:[],
        
      },
      period:7,
      act:0,
      rolelist:[],
      oldrolelist:[],
      rules:{
        title: [
          { required: true, message: '请输入提报标题', trigger: 'blur' },
        ],
        periodtype: [
          { required: true, message: '请选择周期', trigger: 'change' }
        ],
        begindate: [
          { required: true, message: '请选择开始日期', trigger: 'change' }
        ],
        enddate: [
          { validator:this.validateEndDate, required: true, trigger: 'change' }
        ],
        taskdays:[
          { required: true, message: '请输提醒天数', trigger: 'blur' },
        ],
        periodpoint:[
          { validator: this.checkPeriodpoint, trigger: 'blur' }
        ],
        roles: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
      },
    }
  },
  methods:{
    checkPeriodpoint (rule, value, callback) {
      if (value.length === 0 && this.form.periodtype !== 'once') {
        this.error = true
        return callback(new Error('请选择周期'));
      } else {
        this.error = false
        callback();
      }
    },
    validateEndDate(rule, value, callback){
      let start = (new Date(this.form.begdate)).getTime()
      let end = (new Date(this.form.enddate)).getTime()
      if (value === '') {
        callback(new Error('请选择结束日期'));
      } else if (end < start) {
        callback(new Error('结束日期不能小于开始日期'));
      } else {
        // if (this.form.enddate !== '') {
        //   this.$refs['form'].validateField('enddate');
        // }
        callback();
      }
    },
    async queryMainData (fn) {
      const res = await this.$api.requested({
        "id": 20220906150303,
        "version":1,
        "content": {
          "sa_salesforecastmodelid":this.data.sa_salesforecastmodelid
        }
      })
      res.data.roles = res.data.roles.map(e=>{
        return e.roleid
      })
      this.form = res.data
      fn()
    },
    onShow () {
      this.queryRoles()
      this.queryMainData(()=>{
        this.form.periodtype = this.form.periodtype === ''?'once':this.form.periodtype
        this.form.periodpoint = this.form.periodpointchange
      })
    },
    onSubmit () {
      this.$refs['form'].validate(async (valid) => {
        if (!valid) return false
        let data = Object.assign({},this.form)
        data.roles = this.form.roles.map(e=>{
          return {
            "sa_salesforecastmodelroleid":0, 
            "roleid": e
          }
        })
        data.periodtype === 'once'?data.periodtype= '':data.periodtype
        const res = await this.$api.requested({
          "id": 20220906150103,
          "version":1,
          "content": data
        })
        this.tool.showMessage(res,()=>{
          this.$emit('onSuccess')
          this.dialogFormVisible = false
        })
      });
    },
    clickdate (item) {
      this.act = item
      this.form.periodpoint.push(item)
      this.form.periodpoint = [...[],...new Set(this.form.periodpoint)]      
    },
    closeDate (item) {
      this.form.periodpoint = this.form.periodpoint.filter(e=>{
        return e !== item
      })
    },
    handleChange (val) {
      this.form.isrepeat = true
      this.form.periodpoint = []
      val === '月'?this.period = 31:val==='周'?this.period =7:this.form.isrepeat = false
    },
    removeTag (tag) {
      this.oldrolelist = this.oldrolelist.filter(e=>{
        return e.roleid !== tag
      })
    },
    async queryRoles () {
      const res = await this.$api.requested({
        "classname": "webmanage.role.role",
        "method": "query_roleList",
        "content": {
          "pageNumber": 1,
          "pageSize": 1000,
          "where":{
            "condition":"",
            "usertype":"",
            "issystem":1
          }
        }
      })
      this.rolelist = res.data
    },
  },
  mounted () {
  }
}

</script>
<style>
.my-error-panel .el-form-item__error{
  text-indent: 10px;
}
</style>
<style scoped>
.periodTags{
  border:1px solid #dcdfe6;
  min-height:32px;
  /* margin-bottom:18px; */
  padding:0 10px;
  margin-left:10px;
  line-height:32px;
  border-radius: 4px;
  min-width: 400px;
  cursor: pointer;
}
.act{
  background: #dcdfe6;
}
.error{
  border:1px solid red !important;;
}
</style>