<template>
  <div>
    <a-modal
      :title="title"
      :mask-closable="false"
      :visible="visible"
      :width="800"
      :confirm-loading="confirmLoading"
      destroy-on-close
      cancel-text="退出"
      ok-text="保存"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <template slot="footer">
        <a-button @click="handleCancel">退出</a-button>
        <a-button type="primary" @click="handleOk">保存</a-button>
      </template>
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item ref="name" label="被委托人" prop="trusteeUserField">
          <sd-user-picker
            v-model="form.trusteeUserField"
            :single="true"
            :read-only="false"
            :secret-level="userInfo.securityLevel.toString()"
          />
        </a-form-model-item>
        <a-form-model-item label="时间" prop="startDate">
          <a-date-picker
            v-model="form.startDate"
            :default-value="form.startDate"
            :disabled-date="disabledStartDate"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="开始时间"
            @openChange="handleStartOpenChange"
          />
          ~
          <a-date-picker
            v-model="form.finishDate"
            :default-value="form.finishDate"
            :disabled-date="disabledEndDate"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="结束时间"
            :open="endOpen"
            @openChange="handleEndOpenChange"
          />
        </a-form-model-item>
        <a-form-model-item label="全部流程" prop="allFlow">
          <a-radio-group v-model="form.allFlow">
            <a-radio :value="true">
              是
            </a-radio>
            <a-radio :value="false">
              否
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <template v-if="form.allFlow === false">
          <a-form-model-item label="流程名称" prop="flowField">
            <sd-flow-picker v-model="form.flowField" single @change="selectFlow"></sd-flow-picker>
          </a-form-model-item>
          <a-form-model-item label="所有环节" prop="allStep">
            <a-radio-group v-model="form.allStep" @change="selectStep">
              <a-radio :value="true">
                是
              </a-radio>
              <a-radio :value="false">
                否
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <template v-if="form.allStep === false">
            <a-form-model-item label="环节名称" prop="stepField">
              <sd-select
                v-model="form.stepField"
                :options="stepOptions"
                mode="multiple"
              ></sd-select>
            </a-form-model-item>
          </template>
        </template>

        <a-form-model-item label="状态" prop="status">
          <a-radio-group v-model="form.status">
            <a-radio :value="1">
              启用
            </a-radio>
            <a-radio :value="0">
              禁用
            </a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="备注" prop="note">
          <a-input v-model="form.note" :max-length="50" type="textarea" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import storeMixin from '@/common/store-mixin'
import { Message } from 'ant-design-vue'
import errorUtil from '@/common/services/error-util'
import EntrustService from '../entrust-service'
import components from './_import-components/sd-add-import'
export default {
  name: 'SdAdd',
  components,
  mixins: [storeMixin],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    record: {
      type: Object,
      default: function() {},
    },
  },
  data() {
    const trusteeUser = (rule, value, callback) => {
      if (value[0].code === this.userInfo.account) {
        callback(new Error('被委托人不可以为当前操作人'))
      } else {
        callback()
      }
    }
    return {
      endOpen: false,
      confirmLoading: false,
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      form: {
        allFlow: true,
        allStep: true,
        startDate: null,
        finishDate: null,
        flowField: [],
        stepField: [],
        note: '',
        status: 1,
        trusteeUserField: [],
        id: '',
      },
      rules: {
        trusteeUserField: [
          { required: true, trigger: ['change', 'blur'] },
          { validator: trusteeUser, trigger: ['change', 'blur'] },
        ],
        startDate: [{ required: true, trigger: ['change', 'blur'] }],
        allFlow: [{ required: true, trigger: ['change', 'blur'] }],
        status: [{ required: true, trigger: 'blur' }],
        flowField: [{ required: true, trigger: ['change', 'blur'] }],
        stepField: [{ required: true, trigger: ['change', 'blur'] }],
      },
      stepOptions: [],
    }
  },
  created() {
    if (this.record) {
      this.form.id = this.record.id
      EntrustService.detailEntrust(this.record.id)
        .then((data) => {
          data.trusteeUserField = JSON.parse(data.trusteeUserField)
          data.flowField = JSON.parse(data.flowField)
          data.stepField = JSON.parse(data.stepField)
          data.startDate = moment(data.startDate)
          data.finishDate = moment(data.finishDate)
          this.form = data
          // 获取流程环节
          if (data.flowField?.[0] && !data.allStep) {
            this.initFlowStep(data.flowField[0])
          }
        })
        .catch((error) => {
          Message.error({ content: errorUtil.getMessage(error) || '获取委托设置失败' })
        })
    }
  },
  mounted() {},
  methods: {
    selectFlow(flow) {
      this.form.stepField = []
      this.stepOptions = []
      if (!this.form.allStep) {
        this.initFlowStep(flow?.[0])
      }
    },
    initFlowStep(flow) {
      this.stepOptions = []
      if (flow) {
        EntrustService.getFlowStep({ flowId: flow.id }).then((res) => {
          if (res.data && res.data.length > 0) {
            this.stepOptions = res.data.map((item) => ({ id: item.stepId, name: item.name }))
          }
        })
      }
    },
    selectStep() {
      if (!this.form.allStep && this.form.flowField && this.stepOptions.length === 0) {
        this.initFlowStep(this.form.flowField[0])
      }
    },
    handleOk() {
      if (this.form.allFlow === true) {
        this.form.flowField = []
      }
      if (this.form.allStep === true) {
        this.form.stepField = []
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const startTime = this.form.startDate
          const finishTime = this.form.finishDate
          const UserField = this.form.trusteeUserField
          this.formItem = {
            allFlow: this.form.allFlow,
            startDate: moment(startTime).valueOf(),
            finishDate: moment(finishTime).valueOf(),
            flowField: JSON.stringify(this.form.flowField),
            allStep: this.form.allStep,
            stepField: JSON.stringify(this.form.stepField),
            note: this.form.note,
            status: this.form.status,
            trusteeUserField: JSON.stringify(UserField),
            id: this.form.id,
          }
          this.$emit('modalHandleOk', this.formItem)
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.$emit('modalHandleCancel')
    },
    disabledStartDate(startDate) {
      const finishDate = this.form.finishDate
      if (!startDate || !finishDate) {
        return false
      }
      return (
        (startDate && startDate < moment().endOf('day')) ||
        startDate.valueOf() > finishDate.valueOf()
      )
    },
    disabledEndDate(finishDate) {
      const startDate = this.form.startDate
      if (!finishDate || !startDate) {
        return false
      }
      return startDate.valueOf() >= finishDate.valueOf()
    },
    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.date {
  width: 100%;
}
</style>
