<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    :append-to-body="false"
    :close-on-click-modal="false"
    width="70%"
    :before-close="cancel"
  >
    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
      <headerTitle title="基本信息"></headerTitle>
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item
            label="计划编号"
            prop="code"
            style="margin-bottom: 22px">
            <el-input v-model="form.code" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="计划名称"
            prop="planName"
            style="margin-bottom: 22px">
            <el-input v-model="form.planName" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="自动派单"
            prop="automatic"
            style="margin-bottom: 22px">
            <el-select v-model="form.automatic" style="width: 100%">
              <el-option :value="1" label="是"></el-option>
              <el-option :value="0" label="否"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item
            label="计划时间"
            prop="planTimeStart"
            style="margin-bottom: 22px">
            <el-date-picker
              style="width: 100%"
              v-model="planTimeDate"
              @change="(val)=>handleDate(val,'planTimeStart','planTimeEnd')"
              type="datetimerange"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="负责部门"
            prop="responsibleDeptId"
            style="margin-bottom: 22px"
          >
            <ele-tree-select
              clearable
              :data="deptTreeList"
              v-model="form.responsibleDeptId"
              valueKey="id"
              labelKey="name"
              placeholder="请选择"
              @change="changeDeptInfo"
              default-expand-all
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="负责人"
            prop="responsiblePersonId"
            style="margin-bottom: 22px"
          >
            <personSelect
              ref="directorRef"
              v-model="form.responsiblePersonId"
              @selfChange="changeUserInfo"
              :init="false"
            />
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="12">
        <el-col :span="8">
          <el-form-item
            label="紧急程度"
            prop="urgencyLevel"
            style="margin-bottom: 22px">
            <dict-selection dict-name="计划紧急程度" v-model="form.urgencyLevel"></dict-selection>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item
            label="备注"
            prop="remark"
            style="margin-bottom: 22px">
            <el-input type="textarea" v-model="form.remark" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <headerTitle title="任务信息"></headerTitle>
    <taskInfoTable ref="taskInfoRef" v-if="form.trakNoteList.length||dialogType=='add'"
                   :trakNoteList.sync="form.trakNoteList"></taskInfoTable>
    <div slot="footer">
      <el-button type="primary" @click="handleSave(0)">保存</el-button>
      <el-button type="primary" @click="handleSave(1)">提交</el-button>
      <el-button @click="cancel">返回</el-button>
    </div>
  </ele-modal>
</template>
<script>

import fileUpload from "@/components/upload/fileUpload.vue";
import {
  logistictrakplanSaveAPI,
  logistictrakplanUpdateAPI,
  logisticSubmit,
  logistictrakplanInfoAPI
} from "@/api/transportManager/shipManage/index.js";
import RegionsSelect from "@/components/RegionsSelect/index.vue";
import personSelect from "@/components/CommomSelect/person-select.vue";
import {listOrganizations} from "@/api/system/organization";
import taskInfoTable from "./taskInfoTable.vue";

export default {
  name: "add-or-edit-dialog",
  components: {
    personSelect,
    RegionsSelect,
    fileUpload,
    taskInfoTable
  },
  props: {
    addOrEditDialogFlag: {
      type: Boolean,
      default: false
    },
  },
  computed: {},
  data() {
    return {
      dialogType: '',
      title: '',
      deptList: [],
      deptTreeList: [],
      form: {
        id: '',
        code: '',
        planName: '',
        responsiblePersonName: '',
        responsiblePersonId: '',
        responsibleDeptName: '',
        responsibleDeptId: '',
        urgencyLevel: '1',
        automatic: 1,
        planTimeStart: '',
        planTimeEnd: '',
        remark: '',
        trakNoteList: []

      },
      planTimeDate: [],
      rules: {
        planName: [{required: true, message: '请输入计划名称', trigger: 'blur'}],
        responsiblePersonId: [{required: true, message: '请选择负责人', trigger: 'change'}],
        responsibleDeptId: [{required: true, message: '请选择负责部门', trigger: 'change'}],
        planTimeStart: [{required: true, message: '请选择计划时间', trigger: 'change'}],
      }
    }
  },
  created() {

  },
  methods: {
    //初始化
    async init(row = {}, type) {
      this.title = type == 'add' ? '新增' : '修改'
      this.dialogType = type
      await this.getDeptList()
      if (type !== 'add') {
        await this.getInfo(row.id)
      }
    },
    //获取详情
    async getInfo(id) {
      this.form = await logistictrakplanInfoAPI(id)
      this.planTimeDate = [this.form.planTimeStart, this.form.planTimeEnd]
      this.form.urgencyLevel = this.form.urgencyLevel + ''
      // 根据部门获取人员
      this.getUserList(this.form.responsibleDeptId);
    },
    // 获取部门数据
    getDeptList() {
      listOrganizations().then((list) => {
        this.deptList = list;
        this.deptTreeList = this.$util.toTreeData({
          data: list,
          idField: 'id',
          parentIdField: 'parentId'
        });
      });
    },
    // 选择负责人部门
    changeDeptInfo(id) {
      const info = this.deptList.find((e) => e.id == id);
      this.form.responsibleDeptName = info.name;
      this.form.responsiblePersonName = '';
      this.form.responsiblePersonId = '';
      // 根据部门获取人员
      this.getUserList(id);
    },
    // 获取人员数据
    getUserList(groupId) {
      if (groupId) {
        this.$refs.directorRef.getList({groupId});
      }
    },
    //选择人员数据
    changeUserInfo(val, info) {
      this.form.responsiblePersonName = info.name;
    },
    handleDate(val, startDate, endDate) {
      console.log(val);
      if (val) {
        this.form[startDate] = val[0];
        this.form[endDate] = val[1];
      } else {
        this.form[startDate] = '';
        this.form[endDate] = '';
      }
    },
    //
    handleSave(flag) {
      this.$refs.form.validate(async valid => {
        if (!valid) return this.$message.warning('有必填项未填，请检查')
        this.form.trakNoteList = await this.$refs.taskInfoRef.getTableValidate()
        const API = this.dialogType == 'add' ? logistictrakplanSaveAPI : logistictrakplanUpdateAPI
        const id = await API(this.form)
        if (flag) {
          await this.handleSub(id)
        }
        this.$message.success('操作成功')
        this.done()
        this.cancel()
      })
    },
    //提交-开启流程
    async handleSub(id = '') {
      try {
        await logisticSubmit({businessId: id || this.form.id, planId: id || this.form.id})
      } catch (e) {
        this.$message.error(e.message);
      }
    },
    //刷新主列表数据
    done() {
      this.$emit('reload')
    },
    //关闭弹窗
    cancel() {
      this.$emit('update:addOrEditDialogFlag', false)
    }
  }
}
</script>
<style scoped lang="scss">

</style>
