<template>
  <static-content-wrapper
    :designer="designer"
    :field="field"
    :design-state="designState"
    :display-style="field.options.displayStyle"
    :parent-widget="parentWidget"
    :parent-list="parentList"
    :index-of-parent-list="indexOfParentList"
    :sub-form-row-index="subFormRowIndex"
    :sub-form-col-index="subFormColIndex"
    :sub-form-row-id="subFormRowId"
  >
    <gantt
      v-if="showGantt"
      ref="gantt"
      :ganttData.sync="fieldModel"
      :dateType="searchform.DataType"
      :option="ganttConfig.config"
      @rowDbClick="ganttDbClick"
    ></gantt>
  </static-content-wrapper>
</template>

<script>
import StaticContentWrapper from "./static-content-wrapper";
import emitter from "../../../utils/emitter";
import i18n from "../../../utils/i18n";
import fieldMixin from "./fieldMixin";

import gantt from "../components/gantt/index.vue";

export default {
  name: "gantt-widget",
  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件
  mixins: [emitter, fieldMixin, i18n],
  props: {
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,

    designState: {
      type: Boolean,
      default: false,
    },

    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: "",
    },
  },
  components: {
    StaticContentWrapper,
    gantt,
  },
  computed: {},
  beforeCreate() {
    /* 这里不能访问方法和属性！！ */
  },
  data() {
    return {
      // 甘特图配置
      tasks: {
        data: [
          //     {
          //         id: 11,
          //         text: 'Project #1',
          //         // type: gantt.config.types.project,
          //         progress: 0.5,//完成度
          //         open: true,//默认打开
          //         number: '20240227',//显示字段
          //     },
          //     {
          //         toolTipsTxt: '任务#101-001',
          //         id: 12,//任务id
          //         text: '任务#1',//任务名称
          //         start_date: '03-04-2022',//开始时间 日月年
          //         duration: '5',//任务时常
          //         parent: '11',//父级id
          //         progress: 1,//完成度
          //         open: true,//默认打开
          //     },
          //     {
          //         id: 13,
          //         text: '任务#2',
          //         start_date: '03-04-2022',
          //         // type: gantt.config.types.project,
          //         parent: '11',
          //         progress: 0.255,
          //         open: true,
          //     },
          //     {
          //         id: 14,
          //         text: '任务#3',
          //         start_date: '01-04-2022',
          //         duration: '6',
          //         parent: '11',
          //         progress: 0.8,
          //         open: true,
          //     },
          //     {
          //         id: 15,
          //         text: '任务#4',
          //         // type: gantt.config.types.project,
          //         parent: '11',
          //         progress: 0.2,
          //         open: true,
          //     },
          //     {
          //         id: 16,
          //         text: 'Final milestone',
          //         start_date: '15-04-2022',
          //         // type: gantt.config.types.milestone,
          //         parent: '11',
          //         progress: 0,
          //         open: true,
          //     },
          //     {
          //         id: 17,
          //         text: '任务#2.1',
          //         start_date: '03-04-2022',
          //         duration: '2',
          //         parent: '13',
          //         progress: 1,
          //         open: true,
          //     },
          //     {
          //         id: 18,
          //         text: '任务#2.2',
          //         start_date: '06-04-2022',
          //         duration: '3',
          //         parent: '13',
          //         progress: 0.8,
          //         open: true,
          //     },
          //     {
          //         id: 19,
          //         text: '任务#2.3',
          //         start_date: '10-04-2022',
          //         duration: '4',
          //         parent: '13',
          //         progress: 0.2,
          //         open: true,
          //     },
          //     {
          //         id: 20,
          //         text: '任务#2.4',
          //         start_date: '10-04-2022',
          //         duration: '4',
          //         parent: '13',
          //         progress: 0,
          //         open: true,
          //     },
          //     {
          //         id: 21,
          //         text: '任务#4.1',
          //         start_date: '03-04-2022',
          //         duration: '4',
          //         parent: '15',
          //         progress: 0.5,
          //         open: true,
          //     },
          //     {
          //         id: 22,
          //         text: '任务#4.2',
          //         start_date: '03-04-2022',
          //         duration: '4',
          //         parent: '15',
          //         progress: 0.1,
          //         open: true,
          //     },
          //     {
          //         id: 23,
          //         text: 'Mediate milestone',
          //         start_date: '14-04-2022',
          //         // type: gantt.config.types.milestone,
          //         parent: '15',
          //         progress: 0,
          //         open: true,
          //     },
        ],
        // #字段解释
        // 格式 id:数据id
        //     source:开始链接的项目id  ----为tasks.data中数据的id
        //     target:要链接项目的id  ----为tasks.data中数据的id
        //     type: 0--进行-开始  `尾部链接头部`
        //           1--开始-开始  `头部链接头部`
        //           2--进行-进行  `尾部链接尾部`
        //           3--开始-进行  `头部链接尾部`
        // 任务之间连接
        links: [
          { id: "10", source: "11", target: "12", type: "1" },
          { id: "11", source: "11", target: "13", type: "1" },
          { id: "12", source: "11", target: "14", type: "1" },
          { id: "13", source: "11", target: "15", type: "1" },
          { id: "14", source: "23", target: "16", type: "0" },
          { id: "15", source: "13", target: "17", type: "1" },
          { id: "16", source: "17", target: "18", type: "0" },
          { id: "17", source: "18", target: "19", type: "0" },
          { id: "18", source: "19", target: "20", type: "0" },
          { id: "19", source: "15", target: "21", type: "2" },
          { id: "20", source: "15", target: "22", type: "2" },
          { id: "21", source: "15", target: "23", type: "0" },
        ],
      },
      ganttConfig: {},
      ganttInstance: null,
      fieldModel: [],
      searchform: {
        DataType: "day",
        Date: [],
        ProjectId: "",
        PersonId: "",
        PostName: "",
        DepartmentName: "",
      },
      showGantt: false,
    };
  },

  created() {
    /* 注意：子组件mounted在父组件created之后、父组件mounted之前触发，故子组件mounted需要用到的prop
       需要在父组件created中初始化！！ */
    this.registerToRefList();
    this.initEventHandler();

    this.handleOnCreated();
  },

  mounted() {
    this.init();
    this.handleOnMounted();
  },

  beforeDestroy() {
    this.unregisterFromRefList();
    // gantt.destroy();
  },

  methods: {
    ganttDbClick(id) {
      /* console.log('接收到', id);
			let clickRow = this.ganttData.filter((item) => {
				return item.id === id;
			});
			console.log('点击了', clickRow);
			this.detailData = clickRow[0];
            if(!this.detailData.project) return
			this.leftDialogVisible = true; */
    },

    // 初始化
    getDefaultData() {
      return [
        { id: 11, text: "Project #1", type: "project", progress: 0.6, open: true },

        {
          id: 12,
          text: "Task #1",
          start_date: "03-04-2023",
          duration: 5,
          parent: 11,
          progress: 1,
          open: true,
        },
        {
          id: 13,
          text: "Task #2",
          start_date: "03-04-2023",
          type: "project",
          parent: 11,
          progress: 0.5,
          open: true,
        },
        {
          id: 14,
          text: "Task #3",
          start_date: "02-04-2023",
          duration: 6,
          parent: 11,
          progress: 0.8,
          open: true,
        },
        {
          id: 15,
          text: "Task #4",
          type: "project",
          parent: 11,
          progress: 0.2,
          open: true,
        },
        {
          id: 16,
          text: "Final milestone",
          start_date: "15-04-2023",
          type: "milestone",
          parent: 11,
          progress: 0,
          open: true,
        },

        {
          id: 17,
          text: "Task #2.1",
          start_date: "03-04-2023",
          duration: 2,
          parent: 13,
          progress: 1,
          open: true,
        },
        {
          id: 18,
          text: "Task #2.2",
          start_date: "06-04-2023",
          duration: 3,
          parent: 13,
          progress: 0.8,
          open: true,
        },
        {
          id: 19,
          text: "Task #2.3",
          start_date: "10-04-2023",
          duration: 4,
          parent: 13,
          progress: 0.2,
          open: true,
        },
        {
          id: 20,
          text: "Task #2.4",
          start_date: "10-04-2023",
          duration: 4,
          parent: 13,
          progress: 0,
          open: true,
        },
        {
          id: 21,
          text: "Task #4.1",
          start_date: "03-04-2023",
          duration: 4,
          parent: 15,
          progress: 0.5,
          open: true,
        },
        {
          id: 22,
          text: "Task #4.2",
          start_date: "03-04-2023",
          duration: 4,
          parent: 15,
          progress: 0.1,
          open: true,
        },
        {
          id: 23,
          text: "Mediate milestone",
          start_date: "14-04-2023",
          type: "milestone",
          parent: 15,
          progress: 0,
          open: true,
        },
      ];
      let resultData = [
        {
          id: 11,
          text: "Project #1",
          // type: gantt.config.types.project,
          progress: 0.5, //完成度
          open: true, //默认打开
          number: "20240227", //显示字段
        },
        {
          toolTipsTxt: "任务#101-001",
          id: 12, //任务id
          text: "任务#1", //任务名称
          start_date: "03-04-2022", //开始时间 日月年
          duration: "5", //任务时常
          parent: "11", //父级id
          progress: 1, //完成度
          open: true, //默认打开
        },
        {
          id: 13,
          text: "任务#2",
          start_date: "03-04-2022",
          // type: gantt.config.types.project,
          parent: "11",
          progress: 0.255,
          open: true,
        },
        {
          id: 14,
          text: "任务#3",
          start_date: "01-04-2022",
          duration: "6",
          parent: "11",
          progress: 0.8,
          open: true,
        },
        {
          id: 15,
          text: "任务#4",
          // type: gantt.config.types.project,
          parent: "11",
          progress: 0.2,
          open: true,
        },
        {
          id: 16,
          text: "Final milestone",
          start_date: "15-04-2022",
          // type: gantt.config.types.milestone,
          parent: "11",
          progress: 0,
          open: true,
        },
        {
          id: 17,
          text: "任务#2.1",
          start_date: "03-04-2022",
          duration: "2",
          parent: "13",
          progress: 1,
          open: true,
        },
        {
          id: 18,
          text: "任务#2.2",
          start_date: "06-04-2022",
          duration: "3",
          parent: "13",
          progress: 0.8,
          open: true,
        },
        {
          id: 19,
          text: "任务#2.3",
          start_date: "10-04-2022",
          duration: "4",
          parent: "13",
          progress: 0.2,
          open: true,
        },
        {
          id: 20,
          text: "任务#2.4",
          start_date: "10-04-2022",
          duration: "4",
          parent: "13",
          progress: 0,
          open: true,
        },
        {
          id: 21,
          text: "任务#4.1",
          start_date: "03-04-2022",
          duration: "4",
          parent: "15",
          progress: 0.5,
          open: true,
        },
        {
          id: 22,
          text: "任务#4.2",
          start_date: "03-04-2022",
          duration: "4",
          parent: "15",
          progress: 0.1,
          open: true,
        },
        {
          id: 23,
          text: "Mediate milestone",
          start_date: "14-04-2022",
          // type: gantt.config.types.milestone,
          parent: "15",
          progress: 0,
          open: true,
        },
      ];
      return resultData;
    },
    initDefaultConfig() {
      // 格式化日期
      gantt.locale.date = {
        month_full: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        month_short: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
        day_short: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
      };

      gantt.locale.labels = {
        dhx_cal_today_button: "今天",
        day_tab: "日",
        week_tab: "周",
        month_tab: "月",
        new_event: "新建日程",
        icon_save: "保存",
        icon_cancel: "关闭",
        icon_details: "详细",
        icon_edit: "编辑",
        icon_delete: "删除",
        confirm_closing: "请确认是否撤销修改!", //Your changes will be lost, are your sure?
        confirm_deleting: "是否删除计划?",
        section_description: "描述:",
        section_time: "时间范围:",
        section_type: "类型:",
        section_text: "计划名称:",
        section_test: "测试:",
        section_projectClass: "项目类型:",
        taskProjectType_0: "项目任务",
        taskProjectType_1: "普通任务",
        section_head: "负责人:",
        section_priority: "优先级:",
        taskProgress: "任务状态",
        taskProgress_0: "未开始",
        taskProgress_1: "进行中",
        taskProgress_2: "已完成",
        taskProgress_3: "已延期",
        taskProgress_4: "搁置中",
        section_template: "Details",
        /* grid columns */
        column_text: "计划名称",
        column_start_date: "开始时间",
        column_duration: "持续时间",
        column_add: "",
        column_priority: "难度",
        /* link confirmation */
        link: "关联",
        confirm_link_deleting: "将被删除",
        message_ok: "确定",
        message_cancel: "取消",
        link_start: " (开始)",
        link_end: " (结束)",

        type_task: "任务",
        type_project: "项目",
        type_milestone: "里程碑",
        minutes: "分钟",
        hours: "小时",
        days: "天",
        weeks: "周",
        months: "月",
        years: "年",
      };

      console.log(gantt);
      //自适应甘特图的尺寸大小, 使得在不出现滚动条的情况下, 显示全部任务
      gantt.config.autosize = true;
      //只读模式
      gantt.config.readonly = false;
      //是否显示左侧树表格
      gantt.config.show_grid = true;
    },
    initDefaultGantt() {
      //加载默认数据
      this.tasks.data = this.getDefaultData();

      // 格式化日期
      gantt.locale.date = {
        month_full: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        month_short: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        day_full: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
        day_short: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
      };

      gantt.locale.labels = {
        dhx_cal_today_button: "今天",
        day_tab: "日",
        week_tab: "周",
        month_tab: "月",
        new_event: "新建日程",
        icon_save: "保存",
        icon_cancel: "关闭",
        icon_details: "详细",
        icon_edit: "编辑",
        icon_delete: "删除",
        confirm_closing: "请确认是否撤销修改!", //Your changes will be lost, are your sure?
        confirm_deleting: "是否删除计划?",
        section_description: "描述:",
        section_time: "时间范围:",
        section_type: "类型:",
        section_text: "计划名称:",
        section_test: "测试:",
        section_projectClass: "项目类型:",
        taskProjectType_0: "项目任务",
        taskProjectType_1: "普通任务",
        section_head: "负责人:",
        section_priority: "优先级:",
        taskProgress: "任务状态",
        taskProgress_0: "未开始",
        taskProgress_1: "进行中",
        taskProgress_2: "已完成",
        taskProgress_3: "已延期",
        taskProgress_4: "搁置中",
        section_template: "Details",
        /* grid columns */
        column_text: "计划名称",
        column_start_date: "开始时间",
        column_duration: "持续时间",
        column_add: "",
        column_priority: "难度",
        /* link confirmation */
        link: "关联",
        confirm_link_deleting: "将被删除",
        message_ok: "确定",
        message_cancel: "取消",
        link_start: " (开始)",
        link_end: " (结束)",

        type_task: "任务",
        type_project: "项目",
        type_milestone: "里程碑",
        minutes: "分钟",
        hours: "小时",
        days: "天",
        weeks: "周",
        months: "月",
        years: "年",
      };

      console.log(gantt);
      //自适应甘特图的尺寸大小, 使得在不出现滚动条的情况下, 显示全部任务
      gantt.config.autosize = true;
      //只读模式
      gantt.config.readonly = false;
      //是否显示左侧树表格
      gantt.config.show_grid = true;
      // //表格列设置
      gantt.config.columns = [
        {
          name: "text",
          label: "阶段名字",
          tree: true,
          width: "150",
          align: "center",
        },
        // { name: 'number', label: '工单号', tree: false, width: '120', align: 'center', },
        {
          name: "duration",
          label: "工时",
          align: "center",
          template: function (obj) {
            return obj.duration + "天";
          },
        },
        /*{name:"start_date", label:"开始时间", align: "center" },

                {name:"end_date",   label:"结束时间",   align: "center" },*/
      ];
      // 自动延长时间刻度
      gantt.config.fit_tasks = true;
      // 允许拖放
      gantt.config.drag_project = true;
      // 定义时间格式
      gantt.config.scales = [
        { unit: "month", step: 1, date: " %Y,%F" },
        { unit: "day", step: 1, date: " %D ,%j" },
      ];
      // //当task的长度改变时，自动调整图表坐标轴区间用于适配task的长度
      gantt.config.fit_tasks = true;
      // 添加弹窗属性
      gantt.config.lightbox.sections = [
        {
          name: "description",
          height: 70,
          map_to: "text",
          type: "textarea",
          focus: true,
        },
        { name: "type", type: "typeselect", map_to: "type" },
        { name: "time", type: "duration", map_to: "auto" },
      ];
      console.log(this.tasks.data, "检查任务数据"); // 检查任务数据
      // 初始化
      gantt.init(this.$refs.gantt);
      /* *******重点******* */
      gantt.clearAll(); // 清空旧数据
      /* ****************** */
      // 数据解析
      gantt.parse(this.tasks);
    },
    initGantt() {
      gantt.config.tooltip = true;
      // 配置国内日期格式（示例 1：YYYY-MM-DD）
      gantt.config.date_format = "%Y-%m-%d";

      // 可选：配置中文语言包（解决月份/星期显示为英文的问题）
      gantt.locale.labels.section_task = "任务"; // 任务列标题
      gantt.locale.labels.section_project = "阶段"; // 阶段列标题
      gantt.locale.date.months = [
        "01月",
        "02月",
        "03月",
        "04月",
        "05月",
        "06月",
        "07月",
        "08月",
        "09月",
        "10月",
        "11月",
        "12月",
      ];
      gantt.locale.date.days = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      gantt.locale.date.daysShort = ["日", "一", "二", "三", "四", "五", "六"];

      // 若使用格式 2（YYYY年MM月DD日），只需修改 date_format：
      // gantt.config.date_format = '%Y年%m月%d日';

      gantt.clearAll(); // 清空旧数据

      this.initConfig();
      // 初始化
      gantt.init(this.$refs.gantt);

      /* *******重点******* */
      /*
      // 数据解析
      gantt.parse(this.tasks); */
    },
    extendDeeply(result, child) {
      for (var prop in child) {
        // 如果属性本身,就是一个数组或者Json对象,进行深拷贝
        if (child[prop]?.constructor === Object) {
          if (!result[prop]) result[prop] = {};
          // 实现深拷贝
          extendDeeply(result[prop], child[prop]);
        } else {
          result[prop] = child[prop];
        }
      }
      return result;
    },
    initConfig() {
      // this.initDefaultConfig();
      this.ganttConfig = this.handleCustomEvent(this.field.options.ganttConfig) || {};
      /* if (ganttConfig && ganttConfig.config) {
        this.ganttConfig = {};
        this.extendDeeply(gantt, ganttConfig.config);
      } */
    },
    init() {
      if (this.designState) {
        // this.initDefaultGantt();
        this.fieldModel = this.getDefaultData();
        this.showGantt = true;
        return;
      }

      this.initConfig();
      this.showGantt = true;
      // this.initGantt();
      // this.initData();
    },
    /* setValue(value) {
      this.tasks.data = value || [];
      // this.initGantt();
    }, */
    loadData(value) {
      this.showGantt = false;

      // this.setValue(value);
      this.fieldModel = value;
      this.$nextTick(() => {
        this.showGantt = true;
      });
    },
    initData() {
      let reportTemplate = this.getFormRef().reportTemplate;
      let formCode = reportTemplate.formCode;
      let scriptCode = this.field.options.formScriptCode;
      let formScriptEnabled = this.field.options.formScriptEnabled;
      if (!scriptCode || !formScriptEnabled) return;

      this.loading = true;
      this.tasks.data = [];

      this.formHttp({
        scriptCode: scriptCode,
        data: {
          formCode: formCode,
          formVersion: reportTemplate.formVersion,
          data: {
            log_type: oplogTypeCode,
            business_code: business_code,
          },
        },
        addCreateInfo: true,
        queryCreateInfo: true,
        callback: (res) => {
          let rows = res.objx || [];

          this.loadData(rows);
          this.loading = false;
        },
      });
    },
    getGanttRef() {
      return this.$refs.gantt;
    },
    getGanttTarget() {
      return this.$refs.gantt.getGanttTarget();
    },
    getGanttInstance() {
      return this.$refs.gantt.getGanttInstance();
    },
  },
};
</script>

<style lang="scss" scoped>
.firstLevelTask {
  border: none;

  .gantt_task_content {
    // font-weight: bold;
    font-size: 13px;
  }
}

.secondLevelTask {
  border: none;
}

.thirdLevelTask {
  border: 2px solid #da645d;
  color: #da645d;
  background: #da645d;
}

.milestone-default {
  border: none;
  background: rgba(0, 0, 0, 0.45);
}

.milestone-unfinished {
  border: none;
  background: #5692f0;
}

.milestone-finished {
  border: none;
  background: #84bd54;
}

.milestone-canceled {
  border: none;
  background: #da645d;
}

html,
body {
  margin: 0px;
  padding: 0px;
  height: 100%;
  overflow: hidden;
}

.container {
  height: 900px;

  .left-container {
    height: 100%;
  }
}

.left-container {
  height: 600px;
}

.gantt_scale_line {
  border-top: 0;
}

.weekend {
  //background:#f4f7f4!important;
  color: #000000 !important;
}

.gantt_selected .weekend {
  background: #f7eb91 !important;
}

.gantt_task_content {
  text-align: left;
  padding-left: 10px;
}

//上面任务条样式
.gantt_task_scale {
  height: 45px !important;
}

.gantt_task .gantt_task_scale .gantt_scale_cell {
  line-height: 30px !important;
  height: 28px !important;
}
</style>
