<template>
  <div class="title">
    <el-row :gutter="20">
      <!-- 工装 -->
      <el-col :span="12" :xs="24" min-width="500px">
        <el-card class="box-card">
          <template #header>
            <!-- <svg-icon color="#333" icon-class="education" />
            工装列表 -->
            <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="工装名称">
              <el-input v-model="queryParams.platName" placeholder="工装名称" width="120px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="button" @click="queryWorkEquipmentList">查询工装</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="button" @click="handleAdd">新增工装</el-button>
            </el-form-item>
          </el-form>
          </template>

          <!-- <div class="wrapper"> -->
          <el-table v-loading="leftloading" :data="state.lefttableData" border stripe style="width: 100%;"
            :height="lefttableHeight" highlight-current-row @row-click="handleRowClick"
            @current-change="handleCurrentRowChange" :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
            <el-table-column fixed type="index" width="50" align="center" />
            <!-- <el-table-column fixed prop="platId" label="工装ID" header-align="center" width="90" /> -->
            <el-table-column fit prop="platName" label="工装名称" header-align="center" min-width="100" />
            <el-table-column label="工装类型" header-align="center" width="80" align="center">
              <template #default="scope">
                <span v-if="scope.row.staticFlag === '0'">动态</span>
                <span v-if="scope.row.staticFlag === '1'">静态</span>
              </template>
            </el-table-column>
            <el-table-column prop="stdValue" label="静态读数" header-align="center" align="center" width="80" />
            <el-table-column prop="cellNum" label="工位数" header-align="center" align="center" width="70" />
            <el-table-column prop="cellFreeNum" label="空闲数" header-align="center" align="center" width="70" />
            <el-table-column label="使用状态" header-align="center" align="center" width="90">
              <template #default="scope">
                <span v-if="scope.row.usedFlag === '0'">空闲</span>
                <span v-if="scope.row.usedFlag === '1'">拷机中</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="" align="left" width="100">
              <template #default="scope">
                <el-button type="text" @click="handleEdit(0, scope.row)">编辑</el-button>
                <el-button type="text" @click="submitDeleteForm(0, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-config-provider :locale="locale">
            <el-pagination v-model:currentPage="queryParams.page" v-model:page-size="queryParams.rows"
              :page-sizes="[10, 15, 20, 25, 100]" :small="state.small" :disabled="state.disabled"
              :background="state.background" layout="total, sizes, prev, pager, next, jumper" :total="state.total"
              style="text-align: center;margin-top: 10px;height:30px;" @size-change="handleSizeChange"
              @current-change="handleCurrentChange" />
          </el-config-provider>
        </el-card>
      </el-col>
      <!-- 工位 -->
      <el-col :span="12" :xs="24">
        <el-card class="box-card">
          <template #header>
            <svg-icon color="#333" icon-class="education" />
            工位列表-[{{ state.selectworkequipment.platName }}]
          </template>
          <el-table v-loading="rightloading" :data="state.righttableData" border stripe style="width: 100%"
            :height="righttableHeight" @current-change="handleRightCurrentRowChange" highlight-current-row
            :header-cell-style="{ background: '#606266', color: '#FFFFFF' }">
            <el-table-column fixed type="index" width="50" align="center" />
            <!-- <el-table-column fixed prop="cellId" label="工位ID" header-align="center" width="90" /> -->
            <el-table-column fit prop="cellName" label="工位名称" header-align="center" min-width="100" />
            <el-table-column label="工位类型" header-align="center" align="center" width="100">
              <template #default="scope">
                <span v-if="scope.row.staticFlag === '0'">动态</span>
                <span v-if="scope.row.staticFlag === '1'">静态</span>
              </template>
            </el-table-column>
            <el-table-column prop="stdValue" label="标准值" header-align="center" align="center" width="100" />
            <el-table-column label="使用状态" header-align="center" align="center" width="90">
              <template #default="scope">
                <span v-if="scope.row.usedFlag === '0'">空闲</span>
                <span v-if="scope.row.usedFlag === '1'">拷机中</span>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="" align="left" width="150">
              <template #default="scope">
                <el-button type="text" @click="handleEdit(1, scope.row)">编辑</el-button>
                <el-button type="text" @click="submitDeleteForm(1, scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :title="leftdialog.title" v-model="leftdialog.visible" width="450px" draggable center>
      <el-form ref="workequipmentFormRef" :model="leftformData" label-width="100px">
        <!-- <el-form-item label="工装ID:">
          <el-input v-model="leftformData.platId" placeholder="工装ID" width="120px" />
        </el-form-item> -->
        <el-form-item label="工装名称:">
          <el-input v-model="leftformData.platName" placeholder="工装名称" width="120px" />
        </el-form-item>
        <el-form-item label="工装类型:">
          <el-select v-model="leftformData.staticFlag" class="filter-item" placeholder="工装类型" width="150px">
            <el-option v-for="(key, value) in workequipmentTypeMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="静态读数:">
          <el-input v-model="leftformData.stdValue" placeholder="静态读数" width="120px" />
        </el-form-item>
        <el-form-item label="工位数量:">
          <el-input-number v-model="leftformData.cellNum" class="mx-4" />
        </el-form-item>
        <el-form-item label="使用状态:">
          <el-select v-model="leftformData.usedFlag" class="filter-item" placeholder="使用状态" width="150px">
            <el-option v-for="(key, value) in useTypeMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(0)">取消</el-button>
          <el-button type="primary" @click="submitWorkEquipmentForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="rightdialog.title" v-model="rightdialog.visible" width="450px" draggable center>
      <el-form ref="workstationFormRef" :model="rightformData" label-width="100px">
        <el-form-item label="工位名称:">
          <el-input v-model="rightformData.cellName" placeholder="工位名称" width="120px" />
        </el-form-item>
        <el-form-item label="工位类型:">
          <el-select v-model="rightformData.staticFlag" class="filter-item" placeholder="工位类型" width="150px">
            <el-option v-for="(key, value) in workequipmentTypeMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
        <el-form-item label="标准值:">
          <el-input v-model="rightformData.stdValue" placeholder="标准值" width="120px" />
        </el-form-item>
        <el-form-item label="使用状态:">
          <el-select v-model="rightformData.usedFlag" class="filter-item" placeholder="使用状态" width="150px">
            <el-option v-for="(key, value) in useTypeMap" :key="key" :label="key" :value="value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel(1)">取消</el-button>
          <el-button type="primary" @click="submitWorkStationForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, toRef, ref, onMounted } from "vue";
import { ElForm, ElMessage, ElMessageBox, ElTable } from 'element-plus';
import DicChkplatAction from "@/api/systemdictionary/dicchkplat";
import DicChkplatCellAction from "@/api/systemdictionary/dicchkplatcell";
import { DicChkplatQueryParam, DicChkplatModel, DicChkplatCellModel, Dialog } from '@/types';
import { PageResult } from "@/types/api/base";
import zhCn from 'element-plus/lib/locale/lang/zh-cn';

let locale = ref(zhCn)

const queryFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const workequipmentFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致
const workstationFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

const workequipmentTypeMap = {
  0: '动态',
  1: '静态',
};

const useTypeMap = {
  0: '停用',
  1: '使用中',
};
const leftloading = ref(false)
const rightloading = ref(false)
const lefttableHeight = ref(document.documentElement.clientHeight - 360);
const righttableHeight = ref(document.documentElement.clientHeight - 250);

const state = reactive({
  currentType: 0,
  queryParams: { page: 1, rows: 10 } as DicChkplatQueryParam,
  selectworkequipment: {} as DicChkplatModel,
  total: 0,
  small: false,
  background: false,
  disabled: false,
  leftdialog: {} as Dialog,
  rightdialog: {} as Dialog,
  leftformData: {} as DicChkplatModel,
  rightformData: {} as DicChkplatCellModel,
  lefttableData: [] as DicChkplatModel[],
  righttableData: [] as DicChkplatCellModel[]
});

const {
  queryParams,
  total,
  leftdialog,
  rightdialog,
  leftformData,
  rightformData,
  lefttableData,
  righttableData
} = toRefs(state);

const handleAdd = () => {
  state.currentType = 0;
  state.leftformData = {} as DicChkplatModel;
  state.leftformData.cellNum = 15;
  state.leftformData.staticFlag = '1';
  state.leftformData.usedFlag = '1';
  state.leftformData.stdValue = 0;
  state.leftdialog = {
    title: '新增工装',
    visible: true,
    disabled: false,
  };
}
const currentRow = ref()
const rightcurrentRow = ref()
const singleTableRef = ref<InstanceType<typeof ElTable>>()

const setCurrent = (row?: DicChkplatModel) => {
  singleTableRef.value!.setCurrentRow(row)
}

const handleCurrentRowChange = (val: DicChkplatModel | undefined) => {
  currentRow.value = val
}

const handleRightCurrentRowChange = (val: DicChkplatCellModel | undefined) => {
  rightcurrentRow.value = val
}
const handleRowClick = (row: any) => {
  state.selectworkequipment = row;
  queryWorkStationList(row.platId)
}

const handleEdit = (opctype: number, row: any) => {
  if (opctype == 0) {
    state.currentType = 1;
    state.leftformData = JSON.parse(JSON.stringify(row));;
    state.leftdialog = {
      title: '编辑工装',
      visible: true,
      disabled: false,
    };
  }
  else if (opctype == 1) {
    state.currentType = 2;
    state.rightformData = JSON.parse(JSON.stringify(row));;
    state.rightdialog = {
      title: '编辑工位',
      visible: true,
      disabled: false,
    };
  }
}

const handleSizeChange = (val: number) => {
  queryParams.value.rows = val;
  queryWorkEquipmentList();
};

const handleCurrentChange = (val: number) => {
  queryParams.value.page = val;
  queryWorkEquipmentList();
};
const queryWorkEquipmentList = () => {
  leftloading.value = true;
  DicChkplatAction.QueryDicChkplatList(queryParams.value.page, queryParams.value.rows).then(result => {
    if (result.status === 200) {
      const { res, flag, errot } = result.data;
      if (flag != undefined && flag == 1) {
        const pageData = res as PageResult<DicChkplatModel[]>;
        state.lefttableData = pageData.list;
        state.total = pageData.total;
      }
      else { }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
  })
  leftloading.value = false;
};

const queryWorkStationList = (platId: string) => {
  rightloading.value = true;
  DicChkplatCellAction.QueryWorkStationList(platId).then(result => {
    if (result.status === 200) {
      const { res, flag, error } = result.data;
      if (flag != undefined && flag == 1) {
        state.righttableData = res as DicChkplatCellModel[];
      }
      else { }
    }
  }).catch(error => {
    //请求失败时的操作     
    ElMessage.error(error);
  })
  rightloading.value = false;
};

const submitDeleteForm = (opctype: number, row: any) => {
  if (opctype == 0) {
    ElMessageBox.confirm(
      ' 是否删除工装[' + row.platName + ']? ',
      '提示',
      {
        cancelButtonText: '取消',
        confirmButtonText: '确认',
        type: 'warning',
        center: true,
      }
    )
      .then(() => {
        DicChkplatAction.DeleteDicChkplat(row.id).then(result => {
          ElMessage.success('删除成功');
          queryWorkEquipmentList();
        });
      }).then(() => {
        state.selectworkequipment = {} as DicChkplatModel;
        state.righttableData = [] as DicChkplatCellModel[];
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除成功!',
        })
      })
  }
  else if (opctype == 1) {
    ElMessageBox.confirm(
      ' 是否删除工位[' + row.cellName + ']? ',
      '提示',
      {
        cancelButtonText: '取消',
        confirmButtonText: '确认',
        type: 'warning',
        center: true,
      }
    )
      .then(() => {
        DicChkplatCellAction.DeleteWorkStation(row.id).then(result => {
          ElMessage.success('删除成功');

        });
      }).then(() => {
        //queryWorkEquipmentList();
        queryWorkStationList(state.selectworkequipment.platId);
      })
      .then(() => {
        //setCurrent(state.selectworkequipment)
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除成功!',
        })
      })
  }
};

const submitWorkEquipmentForm = () => {
  if (state.currentType == 0) {
    if (!state.leftformData.stdValue) {
      state.leftformData.stdValue = 0;
    }
    DicChkplatAction.AddDicChkplat(state.leftformData).then(result => {
      ElMessage.success('新增成功');
      state.selectworkequipment = result.data as DicChkplatModel;
      cancel(0);
      queryWorkEquipmentList();

    }).then(() => { queryWorkStationList(state.selectworkequipment.platId); });
  }
  else if (state.currentType == 1) {
    DicChkplatAction.EditDicChkplat(state.leftformData).then(result => {
      ElMessage.success('编辑成功');
      state.selectworkequipment = result.data as DicChkplatModel;
      cancel(0);
      queryWorkEquipmentList();
    }).then(() => { queryWorkStationList(state.selectworkequipment.platId); });
  }

};

const submitWorkStationForm = () => {
  DicChkplatCellAction.EditWorkStation(state.rightformData).then(result => {
    ElMessage.success('编辑成功');
    cancel(1);
    queryWorkStationList(state.selectworkequipment.platId);
  });
};


const cancel = (dialogType: number) => {
  if (dialogType == 0) {
    workequipmentFormRef.value.resetFields();
    state.leftdialog.visible = false;
  }
  else {
    workstationFormRef.value.resetFields();
    state.rightdialog.visible = false;
  }
}

onMounted(() => {
  window.onresize = function () {
    lefttableHeight.value = document.documentElement.clientHeight - 360
    righttableHeight.value = document.documentElement.clientHeight - 250
  }

  queryWorkEquipmentList();
})
</script>

<style lang="scss" scoped>
.title {
  font-size: 30px;
}
</style>