<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="8" v-show="false">
            <a-form-item label="ID" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['id']" placeholder="" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="流程发起公司" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-company v-decorator="['company']" multi disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="流程发起时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择流程发起时间" v-decorator="['createTime']" :trigger-change="true" style="width: 100%"  disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="流程发起部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-depart v-decorator="['sysOrgCode']" multi disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="流程发起人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-user-by-dep v-decorator="['createBy']" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="授权人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-user-by-dep v-decorator="['authorizationPerson']" disabled/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="被授权人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-select-user-by-dep v-decorator="['authorizedPerson',validatorRules.authorizedPerson]" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="授权开启时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择授权时间(开启时间)" v-decorator="['privilegedTimeStart',validatorRules.privilegedTimeStart]" @change="dateback" :trigger-change="true" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="授权结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="请选择授权时间(结束时间)" v-decorator="['privilegedTimeEnd',validatorRules.privilegedTimeEnd]" @change="dateback2" :trigger-change="true" style="width: 100%" />
            </a-form-item>
          </a-col>
<!--          <a-col :span="12">-->
<!--            <a-form-item label="是否继续授权" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <j-dict-select-tag  v-decorator="['continueAuthorize', {}]" placeholder="是否继续授权" :type="'radio'" :triggerChange="true" dictCode="authorize_code"/>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
<!--          <a-col :span="12">-->
<!--            <a-form-item label="授权确认时间" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <j-date placeholder="请选择授权时间(确认时间)" v-decorator="['privilegedAffirmedTime',validatorRules.privilegedAffirmedTime]" :trigger-change="true"  style="width: 100%" />-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :span="12">
            <a-form-item label="授权天数" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number v-decorator="['authorizationNumberDays']" placeholder="授权天数" style="width: 100%" disabled/>
            </a-form-item>
          </a-col>
<!--          <a-col :span="12">-->
<!--            <a-form-item label="文件" :labelCol="labelCol" :wrapperCol="wrapperCol">-->
<!--              <a-input v-decorator="['fileId']" placeholder="请输入文件id"  ></a-input>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :span="8" >
            <a-form-item label="文件" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-upload v-decorator="['fileId']" :trigger-change="true"  ></j-upload>
            </a-form-item>
          </a-col>
          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="handleSubmit">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
    <div class="div_process">
      <a-form-item v-if="!disabled" :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button type="primary" :disabled="disabled||btndisabled" @click="handleSubmit">保存</a-button>
        <a-button style="margin-left: 8px" :disabled="disabled" @click="close">取消</a-button>
      </a-form-item>
      <a-form-item v-if="task" :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button type="primary"  @click="passTask">通过</a-button>
        <a-button style="margin-left: 8px"  @click="backTask">驳回</a-button>
      </a-form-item>
    </div>
  </a-spin>
</template>

<script>

  import { httpAction, getAction,getCurrentTime,getStringArry,getRecord } from '@/api/manage'
  import pick from 'lodash.pick'
  import { FormTypes, getRefPromise,validateFormAndTables } from '@/utils/JEditableTableUtil'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDate from '@/components/jeecg/JDate'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import JSwitch from '@/components/jeecg/JSwitch'
  import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDep'
  import JSelectCompany from '../../../components/jeecgbiz/JSelectCompany'
  export default {
    name: 'ProcessPermissionAuthorizationForm',
    components: {
      JFormContainer,
      JDate,
      JDictSelectTag,
      JSwitch,
      JSelectDepart,
      JSelectUserByDep,
      JSelectCompany
    },
    props: {
      /*流程数据*/
      processData:{
        type:Object,
        default:()=>{return {}},
        required:false
      },
      /*是否新增*/
      isNew: {type: Boolean, default: false, required: false},
      /*是否处理流程*/
      task: {type: Boolean, default: false, required: false},
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        form: this.$form.createForm(this),
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        url: {
          getForm:'/actBusiness/getForm',
          add: "/processpermissionauthorization/processPermissionAuthorization/add",
          edit: "/processpermissionauthorization/processPermissionAuthorization/edit",
          queryById: "/processpermissionauthorization/processPermissionAuthorization/queryById"
        },
        btndisabled: false,
        validatorRules: {
          // 'blur'是鼠标失去焦点的时候会触发验证
          authorizedPerson: {rules: [{ required: true, message: '被授权人不能为空!' }]},
          privilegedTimeStart: {rules:[{ required: true, message: '开启时间不能为空!' }]},
          privilegedTimeEnd: {rules:[ { required: true, message: '结束时间不能为空!'}]},
          privilegedAffirmedTime: {rules:[ { required: true, message: '授权时间不能为空!'}]},
          authorizationNumberDays: {rules:[ { required: true, message: '授权天数不能为空!'}]},
        },
      }
    },
    computed: {
      formDisabled(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton(){
        if(this.formBpm===true){
          if(this.formData.disabled===false){
            return true
          }
        }
        return false
      }
    },
    created () {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
      if (!this.isNew){
        this.init();
      }
      let company = sessionStorage.getItem("PARENT_ID");
      let userInfo=sessionStorage.getItem("USER_INFORMATION");
      this.popupCallback(company,userInfo);
    },
    methods: {
      /*回显数据*/
      init(){
        this.btndisabled = true;
        var r = this.processData;
        this.getAction(this.url.queryById,{
          id:r.tableId
        }).then((res)=>{
          if (res.success){
            let formData = res.result;
            formData.tableName = r.tableName;
            this.data = formData;
            console.log("表单回显数据",this.data)
            this.editAfter();
            this.btndisabled = false;
          }else {
            this.$message.error(res.message)
          }
        })
      },
      add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        if (this.data.id != null && this.data.id != '' && this.data.id != undefined && this.data.fileId != null && this.data.fileId != '') {
          //1、文件回显
          this.data = getRecord(this.data)

        }
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.data,'company','createTime','sysOrgCode','createBy','authorizationPerson','authorizedPerson','privilegedTimeStart','privilegedTimeEnd','continueAuthorize','privilegedAffirmedTime','authorizationNumberDays','fileId'))
        })
      },
      close() {
        //todo 关闭后的回调
        this.$emit('close')
      },
      /*通过审批*/
      passTask() {
        this.$emit('passTask')
      },
      /*驳回审批*/
      backTask() {
        this.$emit('backTask')
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },
      handleSubmit () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            let formData = Object.assign(this.model, values);
            formData.procDefId = this.processData.id;
            formData.procDeTitle = this.processData.name;
            formData.title=this.processData.description;
            formData.fileId = getStringArry(formData.fileId)
            if (!formData.tableName)formData.tableName = this.processData.businessTable;
            console.log('格式化后的数据',formData)
            console.log("表单提交数据",formData)
            if (new Date(formData.privilegedTimeStart).getTime()/100>=new Date(formData.privilegedTimeEnd).getTime()/100){
              this.$message.error("授权开始时间不能大于授权结束时间")
              return;
            }
            this.btndisabled = true;
            httpAction(httpurl,formData,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('afterSubmit',formData);
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              this.btndisabled = false;
            })
          }

        })
      },
      popupCallback(company,row){
        let res=JSON.parse(row);
        console.log('获取我的数据',res)
        let param={}
        param.createBy=res.username;
        param.authorizationPerson=res.username;
        param.company=company;
        param.sysOrgCode=res.departIds;
        param.createTime= getCurrentTime();
        this.data=param;
        let fieldval=pick(this.data,'company','createTime','sysOrgCode','createBy','authorizationPerson','authorizedPerson','privilegedTimeStart','privilegedTimeEnd','continueAuthorize','privilegedAffirmedTime','authorizationNumberDays','fileId')
        this.$nextTick(() => {
          this.form.setFieldsValue(fieldval)
        })
      },
      dateback(data){
        if (this.form.getFieldsValue().privilegedTimeEnd !== undefined){
          let date = new Date(this.form.getFieldsValue().privilegedTimeEnd).getTime();
          let time = new Date(data).getTime();
          if (time >= date){
            let  param={}
            param.authorizationNumberDays = Number(0);
            this.data=param;
            let fieldval =pick(this.data,'authorizationNumberDays')
            this.$nextTick(() => {
              this.form.setFieldsValue(fieldval)
            })
            this.$message.warning('开始时间不能大于等于结束时间');
          }else {
            let day = (date - time)/(1000*3600*24)
            let  param={}
            param.authorizationNumberDays = Number(day);
            this.data=param;
            let fieldval =pick(this.data,'authorizationNumberDays')
            this.$nextTick(() => {
              this.form.setFieldsValue(fieldval)
            })
          }
        }
      },
      dateback2(data){
        if (this.form.getFieldsValue().privilegedTimeStart !== undefined){
          let date = new Date(this.form.getFieldsValue().privilegedTimeStart).getTime();
          let time = new Date(data).getTime();
          if (time <= date){
            let  param={}
            param.authorizationNumberDays = Number(0);
            this.data=param;
            let fieldval =pick(this.data,'authorizationNumberDays')
            this.$nextTick(() => {
              this.form.setFieldsValue(fieldval)
            })
            this.$message.warning('结束时间不能小于等于结束时间');
          }else {
            let day = ( time- date)/(1000*3600*24)
            let  param={}
            param.authorizationNumberDays = Number(day);
            this.data=param;
            let fieldval =pick(this.data,'authorizationNumberDays')
            this.$nextTick(() => {
              this.form.setFieldsValue(fieldval)
            })
          }
        }

      },
    }
  }
</script>
<style scoped>
  .div_process{
    margin-top: 30px;
  }
</style>