<template>
  <div class="workmanship">
    <el-card shadow="never">
      <el-form
        label-width="77px"
        class="ele-form-search"
        @keyup.enter.native="search"
        @submit.native.prevent
      >
        <el-row type="flex" :gutter="15">
          <el-col :span="6">
            <el-form-item label="工序编码:" label-width="100px">
              <el-input clearable v-model.trim="where.code" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工序名称:" label-width="100px">
              <el-input clearable v-model.trim="where.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="版本:" label-width="100px">
              <el-input
                clearable
                v-model.trim="where.versions"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row type="flex" :gutter="15">
          <el-col :span="6">
            <el-form-item label="所属工作中心" label-width="100px">
              <el-input clearable v-model.trim="where.workCenterName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <div class="ele-form-actions">
              <el-button
                type="primary"
                class="ele-btn-icon"
                size="small"
                @click="reload"
              >
                查询
              </el-button>
              <el-button size="small" plain>重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <!-- 数据表格 -->
      <ele-pro-table
        class="table_list"
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :need-page="false"
        row-key="id"
      >
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>
          <el-button
           v-if="attributeData.status != 1"
            size="small"
            type="primary"
            icon="el-icon-plus"
            class="ele-btn-icon"
            @click="openEdit()"
          >
            添加工序
          </el-button>
        </template>

        <!-- 展开内容 -->
        <template v-slot:expand="{ row, $index }">
          <div
            style="width: 100%; min-height: 60px"
            v-if="row.categoryParamStepList"
          >
            <ele-pro-table
              :toolbar="false"
              toolsTheme="none"
              ref="table2"
              :need-page="false"
              :datasource="row.categoryParamStepList"
              :columns="columns2"
              :key="row.code + '-' + $index"
            >
              <template v-slot:sort="{ row }">
                <el-input v-model="row.sort"></el-input>
              </template>

              <!-- 默认值 -->
              <template v-slot:defaultValue="{ row }">
                <el-input
                  v-if="
                    row.textType == 1 || row.textType == 4 || row.textType == 5
                  "
                  v-model="row.defaultValue"
                  placeholder="请输入"
                ></el-input>
                <el-select
                  v-if="row.textType == 2"
                  v-model="row.defaultValue"
                  placeholder="请选择"
                >
                  <el-option label="TRUE" :value="'TRUE'" />
                  <el-option label="FALSE" :value="'FALSE'" />
                </el-select>
              </template>

              <!-- 操作列 -->
              <template v-slot:action="{ row }">
                <el-link
                  type="primary"
                  :underline="false"
                  icon="el-icon-edit"
                  @click="editWorkingStep(row)"
                >
                  修改
                </el-link>
                <el-link
                  type="primary"
                  :underline="false"
                  icon="el-icon-view"
                  @click="openStepConfigure(row, true)"
                >
                  详情
                </el-link>
                <el-link
                  type="primary"
                  :underline="false"
                  icon="el-icon-setting"
                  @click="openStepConfigure(row)"
                >
                  配置
                </el-link>
                <el-popconfirm
                  class="ele-action"
                  title="确定要删除当前参数吗？"
                  @confirm="remove2(row)"
                >
                  <template v-slot:reference>
                    <el-link
                
                      type="danger"
                      :underline="false"
                      icon="el-icon-delete"
                    >
                      删除
                    </el-link>
                  </template>
                </el-popconfirm>
              </template>
            </ele-pro-table>
          </div>
        </template>

        <!-- 操作列 -->
        <template v-slot:action="{ row }"  >
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="editWorkingProcedure(row)"
            v-if="attributeData.status != 1"
          >
            修改
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-view"
            @click="openConfigure(row, true)"
          >
            详情
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-setting"
            @click="openStepSetting(row)"
            v-if="attributeData.status != 1"
          >
            工步
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-setting"
            @click="openConfigure(row)"
            v-if="attributeData.status != 1"
          >
            配置
          </el-link>
          <el-popconfirm
            class="ele-action"
            title="确定要删除当前工序吗？"
            @confirm="remove(row)"
          >
            <template v-slot:reference>
              <el-link v-if="attributeData.status != 1" type="danger" :underline="false" icon="el-icon-delete">
                删除
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>

    <ProcessModal
      ref="processModalRef"
      @chooseProcess="chooseProcess"
    ></ProcessModal>

    <ParamModal ref="paramRefs" @chooseModal="chooseModal"></ParamModal>
    <StepModal ref="stepModalRefs" @chooseModal="chooseStepModal"></StepModal>
    <workingProcedure
      ref="workingProcedureRef"
      @chooseProcess="chooseProcess"
    ></workingProcedure>
    <workingStep
      ref="workingStepRef"
      @chooseProcess="chooseProcess"
    ></workingStep>
  </div>
</template>

<script>
  import {
    workingProcedureUpdate,
    getStepListById,
    workingStepSave
  } from '@/api/material/BOM';
  import ProcessModal from './processModal.vue';
  import ParamModal from './ParamModal.vue';
  import StepModal from './StepModal1.vue';
  import workingProcedure from './workingProcedure.vue';
  import workingStep from './workingStep.vue';
  import { getMbomPage, workingStepDelete } from '@/api/material/BOM';
  export default {
    name: 'process',
    components: {
      ProcessModal,
      ParamModal,
      workingProcedure,
      StepModal,
      workingStep
    },
    props: {
      taskParam: Object,
      attributeData: {
        type: Object,
        default: {}
      },
    },

    watch: {
      attributeData: {
        handler(val) {
         this.$nextTick(() => {
          this.reload()
         })
        },
        deep: true,
        immediate: true
      }
    },
    data() {
      return {
        // 表格列配置
        columns: [
          {
            width: 45,
            type: 'expand',
            columnKey: 'categoryParamStepList',
            align: 'center',
            slot: 'expand',
            className: ''
          },
          {
            prop: 'code',
            label: '工序编码',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            prop: 'name',
            label: '工序名称',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            prop: 'versions',
            label: '版本',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            align: 'center',
            prop: 'controlName',
            label: '工序控制码',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'workCenterName',
            label: '所属工作中心',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },

          {
            columnKey: 'action',
            label: '操作',
            width: 300,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true
          }
        ],

        // 表格列配置
        columns2: [
          {
            prop: 'sort',
            slot: 'sort',
            label: '排序',
            minWidth: 60
          },
          {
            prop: 'code',
            label: '工步类型',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            prop: 'name',
            label: '工步编码',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            prop: 'name',
            label: '工序名称',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            prop: 'status',
            slot: 'status',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row) => {
              return ['生效', '失效'][_row.status];
            }
          },

          {
            columnKey: 'action',
            label: '操作',
            align: 'center',
            resizable: false,
            slot: 'action',
            minWidth: 200,
            showOverflowTooltip: true
          }
        ],

        processData: [],
        removeList: [],
        where: {},
        currentTableData: []
      };
    },
    methods: {
      // expandChange(row, rows) {
      //   if (rows.length > 0) {
      //     // 展开
      //     console.log('展开');
      //     getStepListById({
      //       paramId: row.id,
      //       bomCategoryId: this.taskParam.id
      //     }).then((data) => {
      //       row.produceList = data;
      //     });
      //   }
      //   console.log(row);
      //   console.log(rows);
      // },
      openConfigure(row, isView) {
        this.$refs.workingProcedureRef.open(
          row,
          this.taskParam,
          this.currentTableData,
          !!isView
        );
      },
      openStepConfigure(row, isView) {
        this.$refs.workingStepRef.open(row, this.taskParam, !!isView);
      },
      search() {},
      /*配置工艺参数 */
      openSetting(row) {
        this.current = row;
        this.$refs.paramRefs.open(row.produceList, this.current);
      },
      openStepSetting(row) {
        getStepListById({
          paramId: row.id,
          bomCategoryId: this.taskParam.id
        }).then((data) => {
          this.$refs.stepModalRefs.open(data, row, '新增');
        });
      },
      /* 表格数据源 */
      async datasource({ page, limit, where }) {
        let data = await getMbomPage({
          ...where,
          bomCategoryId: this.taskParam.id,
          pageNum: page,
          size: limit
        });
        if (data?.length > 0) {
          this.currentTableData = data[0];
          return data[0].taskParam;
        } else {
          return [];
        }
      },
      editWorkingProcedure(row) {
        this.$refs.processModalRef.open(
          this.taskParam,
          this.currentTableData,
          '修改',
          row
        );
      },
      openEdit() {
        this.$refs.processModalRef.open(
          this.taskParam,
          this.currentTableData,
          '新增'
        );
      },
      editWorkingStep(row) {
        this.$refs.stepModalRefs.open([], row, '修改');
      },
      reload(where) {
        this.$refs.table.reload({ where });
      },
      chooseProcess(data) {

        // let _arr = [...data, ...this.$refs.table.getData()];
        // this.$refs.table.setData([...data, ...this.$refs.table.getData()]);
        // this.$emit('chooseProcess', _arr);
        this.reload();
      },

      chooseModal(data, current) {
        data.map((m) => {
          m.parentId = current.id;
          return {
            ...m
          };
        });

        let tableList = [];
        let clonedArray = [];
        tableList = this.$refs.table.getData();

        clonedArray = JSON.parse(JSON.stringify(tableList));

        clonedArray.forEach((e) => {
          if (e.id == current.id) {
            if (e.hasOwnProperty('produceList')) {
              e.produceList = [...e.produceList, ...data];
            } else {
              e.produceList = [...data];
            }
          }
        });

        this.$refs.table.setData([...clonedArray]);
        this.$emit('chooseProcess', clonedArray);

        this.$nextTick(() => {
          this.$refs.table.toggleRowExpansionAll();
          this.$forceUpdate();
        });
      },
      chooseStepModal(data, current) {
        if (data?.length > 0) {
          let params = data.map((item) => {
            return {
              ...item,
              paramId: current.id,
              stepId: item.id,
              categoryId: this.taskParam.categoryId,
              bomCategoryId: this.taskParam.id,
              categoryCode: this.taskParam.categoryCode
            };
          });
          workingStepSave(params).then((data) => {
            this.$message.success('保存成功');
          });
        }
        this.reload();
        console.log(data);
        console.log(current);
      },
      /* 删除 */
      remove(row) {
        workingProcedureUpdate({
          id: this.currentTableData.id,
          categoryId: this.taskParam.categoryId,
          bomCategoryId: this.taskParam.id,
          categoryCode: this.taskParam.categoryCode,
          taskParam: this.currentTableData.taskParam.filter(
            (item) => item.id !== row.id
          )
        }).then((data) => {
          this.$message.success('删除成功');
          this.reload();
        });
      },

      remove2(row) {
        workingStepDelete([row.id]).then(() => {
          this.$message.success('删除成功');
          this.reload();
        });
        this.$forceUpdate();
      }
    }
  };
</script>
<style lang="scss">
  .workmanship {
    height: 100%;
    .el-card {
      height: 100%;
      .el-card__body {
        height: 100%;
        display: flex;
        flex-direction: column;
        overflow: auto;
        .table_list {
          flex: 1;
          display: flex;
          flex-direction: column;
          .el-table {
            flex: 1;
            overflow-y: auto !important;
            display: flex;
            flex-direction: column;
            .el-table__body-wrapper {
              flex: 1;
            }
          }
        }
      }
    }
  }
</style>
