<template>
  <el-container style="flex-direction: column">
    <el-main id="topContainer" class="nopadding" style="position: relative;margin-bottom: 10px;">
      <div class="right-panel btnsContainer" style=" ">
        <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
        <el-button type="primary" @click="utaskDepuse" v-loading="isloading">任务分解</el-button>
        <el-button type="primary" @click="utaskAssgin" v-loading="isloading">任务下达</el-button>
      </div>
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="粗加工6车间" name="6车间">
          <scTable ref="table1" :apiObj="apiUtask" row-key="id" stripe :params="paramsUtask" :height="tableHeight"
            @row-click="rowClick" @selection-change="handleSelectionChange" hidePagination>
            <el-table-column type="selection" width="40" />
            <el-table-column type="index" width="40" />
            <el-table-column label="任务编号" prop="number">
            </el-table-column>
            <el-table-column label="产品名称" prop="material">
              <template #default="scope">
                {{ scope.row.material_.name }}
              </template>
            </el-table-column>
            <el-table-column label="规格" prop="material">
              <template #default="scope">
                {{ scope.row.material_.specification }}
              </template>
            </el-table-column>
            <el-table-column label="型号" prop="material">
              <template #default="scope">
                {{ scope.row.material_.model }}
              </template>
            </el-table-column>
            <el-table-column label="任务状态" prop="state">
              <template #default="scope">
                <el-tag v-if="scope.row.state !== 40">
                  {{ state_[scope.row.state] }}
                </el-tag>
                <el-tag v-else type="success">
                  {{ state_[scope.row.state] }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="任务量" prop="count">
            </el-table-column>
            <el-table-column label="实际生产数" prop="count_real">
            </el-table-column>
            <el-table-column label="合格数" prop="count_ok">
            </el-table-column>
            <el-table-column label="开工时间" prop="start_date">
            </el-table-column>
            <el-table-column label="完工时间" prop="end_date">
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
              <template #default="scope">
                <el-link type="primary" @click="table_show(scope.row)">
                  查看
                </el-link>
                <el-divider direction="vertical" v-if="scope.row.state == 10"></el-divider>
                <el-link type="primary" @click="table_edit(scope.row)" v-if="scope.row.state == 10">
                  编辑
                </el-link>
                <el-divider direction="vertical" v-if="scope.row.state == 30"></el-divider>
                <el-link type="primary" @click="table_end(scope.row)" v-if="scope.row.state == 30">终止</el-link>
                <el-divider direction="vertical" v-if="scope.row.state == 10 || scope.row.state == 20"></el-divider>
                <el-link type="danger" @click="table_del(scope.row)"
                  v-if="scope.row.state == 10 || scope.row.state == 20">
                  删除
                </el-link>
              </template>
            </el-table-column>
          </scTable>
        </el-tab-pane>
      </el-tabs>
    </el-main>
    <el-main class="nopadding" style="position: relative;height: 50%;">
      <div class="right-panel btnsContainer" v-if="activeNameSub == 'order'">
        <!-- <el-button type="primary" @click="startPlan">排产</el-button> -->
      </div>
      <el-tabs v-model="activeNameSub" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="生产进度" name="rate">
          <GanttComponent class="left-container" :tasks="tasks" :start_date="start_date" :end_date="end_date">
          </GanttComponent>
        </el-tab-pane>
      </el-tabs>
    </el-main>
  </el-container>
  <save-dialog v-if="dialog.save" ref="saveDialog" :activeName="activeName" @success="handleSaveSuccess"
    @closed="dialog.save = false"></save-dialog>
  <el-dialog title="排产" destroy-on-close v-model="visible" @closed="closeAssginVisible">
    <el-form ref="dialogForm" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :md="12" :sm="24">
          <el-form-item label="计划开工日期" prop="start_date">
            <el-date-picker v-model="form.start_date" type="date" placeholder="计划开工日期" value-format="YYYY-MM-DD"
              style="width:90%">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :md="12" :sm="24">
          <el-form-item label="计划完工日期" prop="end_date">
            <el-date-picker v-model="form.end_date" type="date" placeholder="计划完工日期" value-format="YYYY-MM-DD"
              style="width:90%">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-footer>
      <el-button type="primary" :loading="isSaveing" @click="submit">保存</el-button>
      <el-button @click="visible = false">取消</el-button>
    </el-footer>
  </el-dialog>
  <el-drawer title="任务详情" v-model="visibleRecord" :size="800" destroy-on-close @closed="visibleRecord = false">
    <el-container v-loading="loading">
      <el-header>
    <div class="left-panel">
      <el-date-picker placeholder="工作日期" v-model="paramsObj.start_date" type="date" value-format="YYYY-MM-DD" @change="handleMtaskQuery"/>
    </div>
  </el-header>
      <el-main>
        <scTable ref="drawer_table" :apiObj="apiObj" row-key="id" stripe :params="paramsObj">
          <el-table-column type="index" width="50" />
          <el-table-column label="任务编号" prop="number">
          </el-table-column>
          <el-table-column label="工段" prop="mgroup_name" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="数量" prop="count">
          </el-table-column>
          <el-table-column label="工作日期" prop="start_date">
          </el-table-column>
          <el-table-column label="状态" prop="state" show-overflow-tooltip>
            <template #default="scope">
              <el-tag v-if="scope.row.state !== 40">
                {{ state_[scope.row.state] }}
              </el-tag>
              <el-tag v-else type="success">
                {{ state_[scope.row.state] }}
              </el-tag>
            </template>
          </el-table-column>
        </scTable>
      </el-main>
    </el-container>
  </el-drawer>
</template>
<script>
import GanttComponent from '@/components/GanttComponent.vue';
import saveDialog from "./mtask_form.vue";
import { useTransitionFallthroughEmits } from 'element-plus';
export default {
  name: "rparty",
  components: {
    saveDialog, GanttComponent
  },
  data() {
    return {
      state_: {
        10: '创建中',
        14: '已分解',
        20: '已下达',
        30: '生产中',
        40: '已提交'
      },
      ganttHeight: '500px',
      ganttLoading: false,
      projectId: '',
      orderitems: [],
      form: {
        orderitems: [],
        start_date: '',
        end_date: '',

      },
      rules: {
        start_date: [{ required: true, message: "请选择计划开工日期", trigger: "blur" }],
        end_date: [{ required: true, message: "请选择计划完工日期", trigger: "blur" }],
      },
      dialog: {
        save: false,
      },
      apiObj: null,
      paramsObj: { start_date: '' },
      apiUtask: this.$API.pm.utask.list,
      apiOrderItem: this.$API.sam.orderitem.list,
      paramsOrderItem: { utask__isnull: true },
      paramsUtask: { belong_dept__name: '6车间' },
      query: {
        page: 1,
        page_size: 20,
        date: ''
      },
      isloading: false,
      visibleRecord: false,
      isSaveing: false,
      tableHeight: null,
      activeName: '6车间',
      activeNameSub: 'rate',
      visible: false,
      orderitemList: [],
      selectedIds: [],
      utaskDetail: [],
      tasks: {
        data: []
      },
      loading: false,
      end_date: '',
      start_date: '',
    };
  },
  created() {
    //清空gantt数据
    gantt.clearAll();
  },
  mounted() {
    let heights = document.getElementById('topContainer').clientHeight;
    console.log('heights', heights)
    this.tableHeight = (heights - 50) + 'px';
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectedIds = [];
      selection.forEach(item => {
        this.selectedIds.push(item.id)
      });
    },
    //任务分解
    utaskDepuse() {
      let that = this;
      if (that.selectedIds.length > 0) {
        that.isloading = true;
        that.$API.pm.utask.scheduemtasks.req({ ids: that.selectedIds }).then(res => {
          that.$message.success('任务分解成功');
          that.isloading = false;
          that.$refs.table1.refresh();
        }).catch(() => {
          that.isloading = false;
        })
      } else {
        this.$message.error('未选择任何任务')
      }
    },
    //终止
    table_end(row) {
      this.$confirm(`确定终止该任务吗？`, "提示", {
        type: "warning",
      }).then(() => {
        // this.$API.pm.utask.delete.req(row.id).then((res) => {
        //     this.$message.success("删除成功");
        //     this.$refs.table7.refresh();
        //     return res;
        // }).catch((err) => {
        //     return err;
        // });
      }).catch(() => { });
    },
    utaskAssgin() {
      let that = this;
      if (that.selectedIds.length > 0) {
        that.isloading = true;
        that.$API.pm.utask.assgin.req({ ids: that.selectedIds }).then(res => {
          that.$message.success('下达任务成功');
          that.isloading = false;
          that.$refs.table1.refresh();
        }).catch(() => {
          that.isloading = false;
        })
      } else {
        this.$message.error('未选择任何任务')
      }
    },
    selectionOrderItemChange(selection) {
      this.orderitemList = [];
      selection.forEach(item => {
        this.orderitemList.push(item.id)
      });
    },
    //排产
    startPlan() {
      debugger;
      let that = this;
      if (this.orderitemList.length > 0) {
        that.visible = true;
      } else {
        this.$message.error('未选择任何订单明细项目')
      }
    },
    rowClick(row) {
      //获取 mtask
      let that = this;
      that.tasks.data = [];
      that.start_date = row.start_date;
      that.end_date = row.end_date;
      let objItem = {};
      objItem.id = row.id;
      objItem.type = 'utask';
      objItem.number = row.number;
      objItem.count = row.count;
      objItem.text = row.number;
      objItem.material_name = row.material_.name;
      objItem.material_specification = row.material_.specification;
      objItem.material_model = row.material_.model;
      objItem.progress = 1;
      objItem.count_ok = row.count_ok;
      objItem.count_real = row.count_real;
      objItem.count_notok = row.count_notok;
      objItem.state = row.state;
      objItem.start_date = row.start_date;
      objItem.mgroup_name = row.mgroup_name;
      objItem.open = true;
      that.tasks.data.push(objItem)
      this.$API.pm.mtask.list.req({ utask: row.id, page: 0, ordering: 'start_date,mgroup__process__sort' }).then(res => {
        console.log('获取甘特图数据', res)//获取甘特图数据
        res.forEach(item => {
          let obj = {};
          obj.id = item.id;
          obj.type = 'task';
          obj.parent = row.id;
          obj.number = item.number;
          obj.text = item.mgroup_name,
            obj.state = item.state;
          obj.start = item.start_date;
          obj.start_date = item.start_date;
          obj.duration = 1;
          obj.progress = item.count_real / item.count;
          obj.count = item.count;
          obj.count_ok = item.count_ok;
          obj.count_real = item.count_real;
          obj.count_notok = item.count_notok;
          obj.state = item.state;
          obj.utask = item.utask;
          obj.mgroup_name = item.mgroup_name;
          // obj.material_name = item.material_out_.name;
          // obj.material_specification = item.material_out_.specification;
          console.log(obj)
          that.tasks.data.push(obj)
        })
        // console.log(that.tasks.data)
        // console.log('tasks:',that.tasks)
        // 数据解析:将数据解析到gantt列数据中
        gantt.parse(that.tasks);
        // 刷新数据
        gantt.refreshData();
      })
    },
    //自定义新增任务
    addTask(taskId) {
      var $this = this;
      this.$nextTick(() => {
        $this.$refs.taskAdd.init(task, action, parentTask, $this.milestoneOriginalData);
      });
      //删除任务：每次调用gantt内置新增事件时，gantt会直接新增任务到甘特图中，而我们需要的是自定义新增任务
      gantt.deleteTask(taskId);
      //灯箱事件必须返回布尔值，这里使用了自定义灯箱返回false，即不打开灯箱
      return false;
    },
    //添加
    add() {
      this.dialog.save = true;
      this.$nextTick(() => {
        this.$refs.saveDialog.open("add");
      });
    },
    //编辑
    table_edit(row) {
      this.dialog.save = true;
      this.$nextTick(() => {
        this.$refs.saveDialog.open("edit").setData(row);
      });
    },
    //查看
    table_show(row) {
      this.utaskId = row.id;
      this.paramsObj.utask = row.id;
      this.apiObj = this.$API.pm.mtask.list;
      this.visibleRecord = true;
    },
    handleMtaskQuery() {
      this.$refs.drawer_table.queryData(this.paramsObj)
    } ,
    //删除
    async table_del(row) {
      let that = this;
      this.$confirm(`确定删除吗？`, "提示", {
        type: "warning",
      }).then(() => {
        this.$API.pm.utask.delete.req(row.id).then((res) => {
          that.$message.success("删除成功");
          that.$refs.table1.refresh();
          return res;
        }).catch((err) => {
          return err;
        });
      }).catch(() => { });
    },
    //本地更新数据
    handleSaveSuccess() {
      this.$refs.table1.refresh();
    },
    handleQuery() {
      this.$refs.table.queryData(this.query)
    },
    resetQuery() {
      this.query = {};
    },
    closeAssginVisible() { },
    submit() {
      let that = this;
      that.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          that.isSaveing = true;
          that.form.orderitems = that.orderitemList;
          that.form.belong_dept = '3423857962907983872';//6车间
          console.log(that.form)
          that.$API.pm.utask.schedueutasks.req(that.form).then(res => {
            that.visible = false;
            that.$message.success("操作成功");
            that.$refs.table1.refresh();
            that.$refs.table2.refresh();
          }).catch(err => {
            that.visible = false;
          })
        }
      });
    },
  },
};
</script>
<style scoped>
.right-panel>*+* {
  margin-left: 10px;
}

.el-main.nopadding {
  padding: 0 20px 0 20px
}

.btnsContainer {
  display: inline-block;
  position: absolute;
  right: 20px;
  margin-top: 4px;
  z-index: 100
}

.gantt-container {
  height: 30%;
}

.ganntClass {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
}
</style>