<template>
  <ele-modal
    width="65vw"
    :visible.sync="visible"
    v-if="visible"
    :close-on-click-modal="false"
    row-key="code"
    custom-class="ele-dialog-form"
    title="生产前准备"
    @closed="onClose"
    append-to-body
    :maxable="true"
  >
    <ele-pro-table
      ref="table"
      :columns="columns"
      :initLoad="false"
      :datasource="datasource"
      :selection.sync="selection"
      row-key="id"
      @columns-change="handleColumnChange"
      :cacheKey="cacheKeyUrl"
      :page-size="20"
    >
      <template v-slot:toolbar>
        <el-button type="primary" size="mini" @click="batchKittingComplete"
          >批量齐套检查</el-button
        >
      </template>

      <template v-slot:preType="{ row }">
        <span>{{ getTypeLabel(row.preType) }}</span>
      </template>

      <template v-slot:statusStr="{ row }">
        <span v-if="row.statusStr == '缺料'" style="color: red">{{
          row.statusStr
        }}</span>
        <span v-else-if="row.statusStr == '不齐套'" style="color: orange">{{
          row.statusStr
        }}</span>
        <span v-else style="color: green">{{ row.statusStr }}</span>
      </template>

      <template v-slot:action="{ row, $index }">
        <el-link
          type="primary"
          :underline="false"
          @click="kittingComplete(row, $index)"
        >
          齐套检查
        </el-link>

        <el-link
          type="primary"
          :underline="false"
          @click="taskAssignment"
          v-if="row.statusStr == '缺料' && row.preType == '6'"
        >
          任务派单
        </el-link>
      </template>
    </ele-pro-table>

    <el-dialog
      title="任务派单"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      append-to-body
    >
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <el-form-item label="分管部门：">
          <ele-tree-select
            clearable
            :data="groupList"
            filterable
            v-model="form.executeGroupId"
            valueKey="id"
            labelKey="name"
            placeholder="请选择"
            @change="change_principalDep"
            default-expand-all
          />
        </el-form-item>

        <el-form-item label="技术员：" prop="executorId">
          <el-select
            v-model="form.executorId"
            placeholder="请选择"
            style="width: 100%"
            @change="leaderListChange"
          >
            <el-option
              v-for="item in leaderList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入内容"
            v-model="form.remake"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="batchConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <kitting-complete ref="kittingCompleteRef"></kitting-complete>
  </ele-modal>
</template>

<script>
  import { completenessCheck, taskReleaseWork } from '@/api/productionPlan';
  import { listOrganizations, getUserPage } from '@/api/system/organization';
  import kittingComplete from './kittingComplete.vue';
  export default {
    components: { kittingComplete },
    data() {
      // 1主材料 2辅材料 3工装 4工艺文件 5NC代码 6人员
      return {
        visible: false,
        cacheKeyUrl: 'checkProductionPreparationsKey',
        selection: [],
        planId: '',
        typeList: [
          {
            value: 1,
            label: '主材料齐套'
          },
          {
            value: 2,
            label: '辅材料齐套'
          },
          {
            value: 3,
            label: '工装齐套'
          },
          {
            value: 4,
            label: '工艺文件齐套'
          },
          {
            value: 5,
            label: 'NC代码齐套'
          },
          {
            value: 6,
            label: '人员齐套'
          }
        ],
        groupList: [],
        leaderList: [],
        form: {
          executeGroupName: '',
          executeGroupId: '',
          executorName: '',
          executorId: '',
          remake: ''
        },
        dialogVisible: false,
        rules: {
          executorId: [
            { required: true, message: '请选择技术人员', trigger: 'blur' }
          ]
        },
        itemData: {}
      };
    },

    created() {
      console.log(this.$store.state.user.info, '用户信息');
      this.getGs();
    },

    computed: {
      columns() {
        return [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            fixed: 'left',
            reserveSelection: true
          },
          {
            width: 55,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            label: '序号',
            fixed: 'left'
          },
          {
            prop: 'preType',
            slot: 'preType',
            align: 'center',
            label: '名称'
          },
          {
            prop: 'statusStr',
            slot: 'statusStr',
            align: 'center',
            label: '状态'
          },
          {
            prop: 'approveDate',
            align: 'center',
            label: '校验时间'
          },
          {
            prop: 'approveName',
            align: 'center',
            label: '校验人',
            showOverflowTooltip: true
          },
          {
            columnKey: 'action',
            label: '操作',
            align: 'center',
            resizable: false,
            slot: 'action',
            fixed: 'right',
            showOverflowTooltip: true
          }
        ];
      }
    },

    methods: {
      datasource({ page, where, limit }) {
        let pageNum = page;
        let size = limit;
        where.planId = this.planId;
        const res = completenessCheck({ ...where, pageNum, size });

        return res;
      },

      reload(where) {
        this.$nextTick(() => {
          if (this.$refs.table && this.$refs.table.reload)
            this.$refs.table.reload({ page: 1, where: where });
        });
      },

      async getGs() {
        await listOrganizations().then((list) => {
          this.groupList = this.$util.toTreeData({
            data: list,
            idField: 'id',
            parentIdField: 'parentId'
          });
        });
      },

      getTypeLabel(value) {
        const item = this.typeList.find((it) => it.value === value);
        return item ? item.label : '';
      },

      open(item) {
        this.visible = true;
        this.itemData = item;
        this.planId = item.id;

        if (this.planId) {
          this.reload();
        }
      },

      handleColumnChange() {},

      onClose() {
        this.planId = '';
        this.visible = false;
      },

      handleClose() {
        this.dialogVisible = false;
      },
      kittingComplete(item, index) {
        if (item.preType == '5' || item.preType == '6') {
          this.$confirm('是否确认齐套?', '提示', {
            confirmButtonText: '齐套',
            cancelButtonText: '不齐套',
            type: 'warning'
          })
            .then(() => {
              // approveDate: null;
              // approveId: '';
              // approveName: '';
              item.approveDate = this.getNowDate();
              item.statusStr = '齐套';
              this.$forceUpdate();
            })
            .catch(() => {
              item.approveDate = this.getNowDate();
              item.statusStr = '不齐套';
              this.$forceUpdate();
            });
        } else {
          const list = [this.itemData];
          this.$refs.kittingCompleteRef.open(list);
        }
      },

      getNowDate() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hour = String(now.getHours()).padStart(2, '0');
        const minute = String(now.getMinutes()).padStart(2, '0');
        const second = String(now.getSeconds()).padStart(2, '0');

        const currentTime = `${year}-${month}-${day} ${hour}:${minute}:${second}`;

        return currentTime;
      },

      taskAssignment() {
        this.dialogVisible = true;
      },

      change_principalDep(id) {
        const node = this.findNodeById(this.groupList, id);
        this.form.executeGroupName = node ? node.name : '';
        this.form.executorId = '';
        this.form.executorName = '';

        this.getUserPage();
      },

      leaderListChange(id) {
        const item = this.leaderList.find((it) => it.id === id);
        this.form.executorName = item.name;
      },

      findNodeById(list, id) {
        for (const item of list) {
          if (item.id === id) return item;
          if (item.children) {
            const found = this.findNodeById(item.children, id);
            if (found) return found;
          }
        }
        return null;
      },

      async getUserPage() {
        if (!this.form.executeGroupId) return (this.leaderList = []);
        let par = {
          groupId: this.form.executeGroupId,
          size: 999
        };
        await getUserPage(par).then((res) => {
          this.leaderList = res.list;
        });
      },

      async batchConfirm() {
        const valid = await this.$refs.form.validate().catch(() => false);
        if (!valid) return;

        const loading = this.$loading({
          lock: true,
          text: '派单中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        await taskReleaseWork({
          ...this.form,
          productionPlanId: this.itemData.id,
          eventType: 1
        })
          .then(() => {
            loading.close();
            this.form = {
              executeGroupName: '',
              executeGroupId: '',
              executorName: '',
              executorId: '',
              remake: ''
            };
            this.dialogVisible = false;
            this.reload();
          })
          .catch(() => {
            loading.close();
          });
      },
      batchKittingComplete() {}
    }
  };
</script>

<style></style>
