<template>
  <el-dialog :visible.sync="visible" :title="title" :close-on-click-modal="false" :close-on-press-escape="false"
    width="950px" top="5vh" class="dialog-h" :before-close="handleCancel">
    <div class="dialog-h-content scroll-h">
      <el-form ref="ref_form" :inline="true" :model="formData" :rules="dataRule" class="form">
        <el-form-item label="任务名称" prop="title" label-width="150px">
          <el-input v-model.trim="formData.title" size="small" clearable placeholder="请输入"
            class="item_width_1"></el-input>
        </el-form-item>
        <el-form-item label="所属组织" prop="agencyId" label-width="150px">
          <el-cascader style="width: 100%;" size="small" v-model="cascaderAgencyId" :options="organizeOptions"
            :props="{ checkStrictly: true, multiple: false, value: 'value', label: 'label', children: 'children' }"
            :show-all-levels="false" @change="handleOrgChange" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="有效期" prop="timeRange" label-width="150px">
          <div class="item_width_1" style="display: flex;">
            <el-date-picker v-model="formData.startTime" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              placeholder="开始时间" :picker-options="startTimePickerOptions" />
            <div style="margin: 0 10px;">至</div>
            <el-date-picker v-model="formData.endTime" type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              placeholder="结束时间" :picker-options="endTimePickerOptions" />
          </div>

        </el-form-item>
      </el-form>

    </div>

    <div class="div_btn">
      <el-button size="small" @click="handleCancel" :loading="btnDisable">取 消</el-button>
      <el-button size="small" type="primary" :loading="btnDisable" @click="handleConfirm">确 定</el-button>
    </div>

  </el-dialog>
</template>

<script>
import _ from 'lodash'
import dayjs from 'dayjs'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
import Tinymce from '@c/tinymce2/index.vue'
import UploadImage from '@/views/modules/plugins/rent/upload-image.vue'
import ElImageViewer from "element-ui/packages/image/src/image-viewer"

const defaultFormData = {
  id: undefined,
  title: '',
  agencyId: '',
  startTime: '',
  endTime: '',
}

let loading // 加载动画
export default {
  name: 'keyTaskDialog',
  components: { Tinymce, UploadImage, ElImageViewer },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      formData: _.cloneDeep(defaultFormData),
      btnDisable: false,
      cascaderAgencyId: [],
      organizeOptions: [],
    }

  },

  created() {
    this.getOptions()
  },

  methods: {
    // 获取所属组织
    async getOptions() {
      const { data } = await requestPost("/gov/org/customeragency/orgtree", {});
      this.organizeOptions = data ? [this.computeOption(data)] : []
    },
    // 格式化数据
    computeOption(opt) {
      return {
        label: opt.agencyName,
        value: opt.agencyId,
        type: "agency",
        children: [
          ...this.processDepartmentList(opt.departmentList),
          ...this.processGridList(opt.gridList),
          ...this.processSubAgencyList(opt.subAgencyList),
        ],
      };
    },
    // 处理部门列表
    processDepartmentList(departmentList) {
      return (departmentList || []).map((item) => ({
        label: item.deptName,
        value: item.deptId,
        type: "dept",
        typeName: "部门",
      }))
    },
    // 处理网格列表
    processGridList(gridList) {
      return (gridList || []).map((item) => ({
        label: item.gridName,
        value: item.gridId,
        type: "grid",
        typeName: "网格",
      }))
    },
    // 处理子机构列表
    processSubAgencyList(subAgencyList) {
      return (subAgencyList || []).map((item) => this.computeOption(item))
    },
    // 详情数据
    async initForm(row) {
      if (row && row.id) {
        this.startLoading()
        let url = `/actual/base/importantTask/${row.id}`
        const { data, code, msg } = await requestPost(url)
        this.formData = data ? data : _.cloneDeep(defaultFormData)
      }
      this.endLoading();
    },
    // 修改组织级联选择器值
    handleOrgChange(val) {
      this.formData.agencyId = val[val.length - 1];
      this.$refs['ref_form'].validateField('agencyId');
    },

    async handleConfirm() {
      this.$refs['ref_form'].validate(async valid => {
        if (valid) {
          this.btnDisable = true;
          let url = this.formData.id ? '/actual/base/importantTask/update' : '/actual/base/importantTask/save'
          this.formData.startTime = dayjs(this.formData.startTime).startOf('day').format("YYYY-MM-DD HH:mm:ss");
          this.formData.endTime = dayjs(this.formData.endTime).endOf('day').format("YYYY-MM-DD HH:mm:ss");
          this.formData.releaseTime = this.formData.releaseTime || dayjs().format("YYYY-MM-DD HH:mm:ss")
          const { data, code, internalMsg } = await requestPost(url, this.formData)
          if (code === 0) {
            this.$message.success(this.formData.id ? '更新成功' : '新增成功')
            this.resetData()
            this.$emit('update:visible', false)
            this.$emit('success')
          } else {
            this.$message.error(internalMsg)
          }
          this.btnDisable = false
        }
      })
    },

    // 取消
    handleCancel() {
      this.resetData()
      this.$emit('update:visible', false)

    },

    resetData() {
      this.formData = _.cloneDeep(defaultFormData)
      this.$refs['ref_form'].resetFields()
      this.cascaderAgencyId = []
    },
    // 开启加载动画
    startLoading() {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading() {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    dataRule() {
      return {
        title: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        agencyId: [
          { required: true, message: '请选择所属组织', trigger: 'change' }
        ],
        timeRange: [
          {
            required: true, validator: (rule, value, callback) => {
              if (!this.formData.startTime && !this.formData.endTime) {
                return callback(new Error('请选择有效期'));
              } else if (!this.formData.startTime) {
                return callback(new Error('请选择开始时间'));
              } else if (!this.formData.endTime) {
                return callback(new Error('请选择结束时间'));
              } else {
                callback();
              }
            }, trigger: 'change'
          }
        ]

      }
    },
    startTimePickerOptions() {
      return {
        disabledDate: (time) => {
          if (this.formData.endTime) {
            return time.getTime() > new Date(this.formData.endTime).getTime();
          }
          return false;
        }
      };
    },
    endTimePickerOptions() {
      return {
        disabledDate: (time) => {
          if (this.formData.startTime) {
            return time.getTime() < new Date(this.formData.startTime).getTime();
          }
          return false;
        }
      };
    }
  }

}
</script>


<style lang="scss" scoped>
.form {
  margin-top: 16px;
}

.item_width_1 {
  width: 560px;

  /deep/.tox .tox-dialog {
    z-index: 20000;
  }
}

.div_btn {
  width: 100%;
  text-align: right;
  padding-right: 20px;
}
</style>
