<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    :append-to-body="true"
    :close-on-click-modal="false"
    width="60%"
    :before-close="cancel"
    :maxable="true"
    :resizable="true"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      class="el-form-box"
      :disabled="title == '详情'"
    >
      <headerTitle title="产品信息"> </headerTitle>
      <el-row>
        <el-col :span="12">
          <el-form-item label="编码" prop="code">
            <el-input
              clearable
              readonly
              v-model="form.code"
              @click.native="$refs.produceRef.open()"
              placeholder="请选择"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input clearable disabled v-model="form.name" placeholder=" " />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="BOM类型" prop="bomCategory">
            <el-select
              v-model="form.bomCategory"
              @change="changeProductType"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item of bomCategoryList"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="BOM版本" prop="bomId">
            <el-select
              v-model="form.bomId"
              @change="changeBomId"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item of bomVersionList"
                :key="item.id"
                :label="item.name + '(V' + item.versions + '.0)'"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工艺路线" prop="produceRoutingId">
            <el-select
              v-model="form.produceRoutingId"
              @change="changeRoutingList"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item of routingList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工厂名称:" prop="factoriesId">
            <el-select
              style="width: 100%"
              clearable
              v-model="form.factoriesId"
              placeholder="请选择所属工厂"
            >
              <el-option
                v-for="item in factoryList"
                :label="item.name"
                :value="item.id"
                :key="item.id"
                @click.native="change_factoryId(item)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <headerTitle title="工位节拍"> </headerTitle>
      <ele-pro-table
        :columns="columns"
        :datasource="form.list"
        ref="table"
        height="400px"
        full-height="calc(100vh - 116px)"
        :needPage="false"
        :selection.sync="selection"
      >
        <template v-slot:toolbar>
          <div style="display: flex">
            <el-form-item label="工序名称" prop="operationId">
              <el-select
                v-model="form.operationId"
                style="width: 230px"
                v-if="form.produceRoutingId"
              >
                <el-option
                  v-for="item of taskList"
                  :key="item.sourceTaskId"
                  :label="item.name"
                  :value="item.sourceTaskId"
                  @click.native="changeOperationId(item)"
                ></el-option>
              </el-select>
              <el-input
                v-if="!form.produceRoutingId"
                style="width: 230px"
                readonly
                :value="form.operationName"
                placeholder=" "
              />
              <el-button
                v-if="!form.produceRoutingId"
                size="small"
                type="primary"
                style="margin-left: 10px"
                @click.native="taskinstanceDialogFlag = true"
                >选择
              </el-button>
            </el-form-item>
            <el-form-item label="工序节拍(分)" prop="cycleTime">
              <el-input
                clearable
                style="width: 230px"
                disabled
                :value="cycleTime"
                placeholder=" "
              />
            </el-form-item>
            <el-form-item label-width="0">
              <el-button
                size="small"
                type="primary"
                style="margin-left: 10px"
                @click.native="$refs.stationBeatDialogRef.open()"
                >新增工位
              </el-button>
            </el-form-item>
          </div>
        </template>
        <template v-slot:stationCycleTime="{ row, $index }">
          <el-form-item
            label-width="0"
            :prop="'list.' + $index + '.stationCycleTime'"
            :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
          >
            <el-input
              clearable
              v-model.number="row.stationCycleTime"
              placeholder="请输入"
            />
          </el-form-item>
        </template>
        <template v-slot:priority="{ row, $index }">
          <el-form-item
            label-width="0"
            :prop="'list.' + $index + '.priority'"
            :rules="[{ required: true, message: '请输入', trigger: 'blur' }]"
          >
            <el-input
              clearable
              v-model.number="row.priority"
              placeholder="请输入"
            />
          </el-form-item>
        </template>

        <template v-slot:remark="{ row }">
          <el-input clearable v-model="row.remark" placeholder="请输入" />
        </template>
        <template v-slot:columnRequired="{ column }">
          <span class="is-required">{{ column.label }}</span>
        </template>
      </ele-pro-table>
    </el-form>
    <div slot="footer">
      <el-button
        type="primary"
        @click="save()"
        v-lodading="loading"
        v-if="title != '详情'"
        >保存</el-button
      >

      <el-button @click="cancel">返回</el-button>
    </div>
    <ProductModal
      ref="produceRef"
      @changeParent="produceConfirm"
    ></ProductModal>
    <taskinstanceDialog
      ref="taskinstanceDialogRef"
      v-if="taskinstanceDialogFlag"
      @saveTaskInstance="changeOperationId"
      :visible.sync="taskinstanceDialogFlag"
    ></taskinstanceDialog>
    <stationBeatDialog
      ref="stationBeatDialogRef"
      @save="stationBeatAdd"
      :disabledTableList="this.form.list"
    ></stationBeatDialog>
  </ele-modal>
</template>
<script>
  const defForm = {
    code: '', //编码
    name: '', //名称
    productId: '', //物品id
    factoriesId: '', //工厂id
    factoriesName: '', //工厂名称
    bomVersion: '', //bom版本
    bomId: '', //bom版本id
    bomCategory: '', //bom类型
    brandNo: '', //品牌
    specification: '', //规格
    modelType: '', //型号
    produceRoutingId: '', //	工艺路线
    produceRoutingName: '', //	工艺路线名称
    cycleTime: '', //	工序节拍
    operationName: '', //	工序名称
    operationId: '', //	工序id
    list: [] //表格数据
  };
  import { getFactoryarea } from '@/api/factoryModel';
  import ProductModal from '@/components/productList/product-list.vue';
  import taskinstanceDialog from '@/components/procedure/taskinstanceDialog.vue';
  import stationBeatDialog from '@/views/factoryModel/station/components/stationBeatDialog.vue';
  import {
    saveOrUpdate,
    getById,
    listBomType,
    bomListByPlan,
    bomRoutingList,
    listByRoutingIds,
    selectFactoryWorkstation
  } from '@/api/productionScheduling/stationBeat';
  export default {
    components: { ProductModal, taskinstanceDialog, stationBeatDialog },
    computed: {},
    data() {
      return {
        lodading: false,
        title: '',
        addOrEditDialogFlag: false,
        taskinstanceDialogFlag: false,
        form: { ...defForm },
        rules: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'change' }
          ],
          // factoriesId: [
          //   { required: true, message: '请选择工厂', trigger: 'change' }
          // ],
          // bomId: [
          //   { required: true, message: '请选择BOM版本', trigger: 'change' }
          // ],
          // bomCategory: [
          //   { required: true, message: '请选择BOM类型', trigger: 'change' }
          // ],
          // produceRoutingId: [
          //   { required: true, message: '请选择工艺路线', trigger: 'change' }
          // ],
          code: [{ required: true, message: '编码不能为空', trigger: 'change' }]
        },
        factoryList: [],
        selection: [],
        productionLineList: [],
        columns: [
          {
            width: 60,
            type: 'index',
            columnKey: 'index',
            label: '序号',
            align: 'center',
            fixed: 'left'
          },
          {
            prop: 'workstationName',
            label: '工位名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180
          },
          {
            prop: 'deviceCode',
            label: '设备编码',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180
          },
          {
            prop: 'deviceName',
            label: '设备名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180
          },
          {
            prop: 'model',
            label: '型号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180
          },
          {
            prop: 'deviceType',
            label: '设备类型',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180
          },

          {
            prop: 'stationCycleTime',
            slot: 'stationCycleTime',
            headerSlot: 'columnRequired',
            label: '工位节拍(分钟)',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 180
          },
          {
            prop: 'priority',
            slot: 'priority',
            headerSlot: 'columnRequired',
            label: '优先顺序',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 120
          },
          {
            prop: 'remark',
            slot: 'remark',
            label: '备注',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 200
          }
        ],
        loading: false,
        bomCategoryList: [],
        bomVersionList: [],
        routingList: [],
        taskList: []
      };
    },
    mounted() {},
    created() {
      this.getFactoryList();
    },
    computed: {
      cycleTime() {
        let cycleTime = this.form.list.reduce((pre, cur) => {
          return pre + Number(cur.stationCycleTime);
        }, 0);
        this.form.cycleTime =
          cycleTime / this.form.list.length / this.form.list.length;
        return cycleTime / this.form.list.length / this.form.list.length || 0;
      }
    },

    methods: {
      //初始化
      async open(row = {}, type) {
        this.addOrEditDialogFlag = true;
        this.title = type == 'add' ? '新增' : type == 'edit' ? '修改' : '详情';

        if (type !== 'add') {
          this.form = await getById(row.id);
          this.form.list.forEach((item, index) => {
            item.key = index;
          });
          this.getBomInfo(this.form.productId);
          this.changeProductType('init');

          if (this.form.factoriesId) {
            this.change_factoryId({ id: this.form.factoriesId });
          }
        }
      },
      handParent() {
        this.form.list.push({
          productionLineName: '',
          productionLineId: '',
          stationCycleTime: '',
          remark: '',
          key: this.form.list?.length || 0
        });
      },
      async getFactoryList() {
        const { list } = await getFactoryarea({
          pageNum: 1,
          size: 999,
          type: 1,
          enable: 1
        });
        this.factoryList = list || [];
      },
      async change_factoryId(item) {
        const { list } = await getFactoryarea({
          pageNum: 1,
          size: 999,
          type: 4,
          factoryId: item.id,
          enable: 1
        });
        this.productionLineList = list || [];
        this.form.factoriesName = item.name;
      },
      change_productionLineId(item, index) {
        this.$set(this.form.list[index], 'productionLineName', item.name);
      },
      produceConfirm(data) {
        this.form.name = data[0].name;
        this.form.code = data[0].code;
        this.form.productId = data[0].id;
        this.form.brandNo = data[0].brandNum;
        this.form.modelType = data[0].modelType;
        this.form.specification = data[0].specification;
        this.produceCancel();
        this.getBomInfo(data[0].id);
      },
      produceCancel() {
        this.form.bomCategory = '';
        this.bomCategoryList = [];
        this.form.bomVersion = '';
        this.form.bomId = '';
        this.bomVersionList = [];
        this.routingList = [];
        this.form.produceRoutingId = '';
        this.form.produceRoutingName = '';
        this.produceRoutingList = [];
        this.form.operationId = '';
        this.form.operationName = '';
        this.taskList = [];
        this.form.list = [];
      },

      // 获取bom信息
      async getBomInfo(id) {
        const res = await listBomType({ categoryId: id });
        if (!res || res.length == 0) return;
        let bomMap = {
          2: { code: '2', name: 'MBOM' },
          3: { code: '3', name: 'ABOM' }
        };
        let arr = [];
        res.map((item) => {
          if (bomMap[item.bomType]) {
            arr.push(bomMap[item.bomType]);
          }
        });
        this.bomCategoryList = arr;
      },

      // 根据bom类型和产品id获取bom版本
      async changeProductType(type) {
        let data = await bomListByPlan({
          bomType: this.form.bomCategory,
          categoryId: this.form.productId
        });
        this.bomVersionList = data;
        if (data.length) {
          if (type != 'init') {
            this.form.bomId = data[0].id;
            this.form.bomVersion = data[0].versions;
          }
          this.changeBomId(type);
        }
      },
      async changeBomId(type) {
        const res = await bomRoutingList(this.form.bomId);
        let arr = res || [];
        this.routingList = arr;
        if (type != 'init') {
          this.form.bomVersion = this.bomVersionList.find(
            (item) => item.id == this.form.bomId
          )?.versions;
          this.taskList = [];
          this.form.produceRoutingId = '';
          this.form.produceRoutingName = '';
          this.form.operationName = '';
          this.form.operationId = '';
          this.form.list = [];
        }

        if (arr.length) {
          if (type != 'init') {
            this.form.produceRoutingId = arr[0].id;
            this.form.produceRoutingName = arr[0].name;
          }
          this.changeRoutingList(type);
        }
      },
      async changeRoutingList(type) {
        const res = await listByRoutingIds([this.form.produceRoutingId]);
        let arr = res || [];
        this.taskList = arr;
        if (type != 'init') {
          this.form.operationName = '';
          this.form.operationId = '';
          this.form.list = [];
        }
      },
      async changeOperationId(item) {
        this.form.operationName = item.name;
        this.form.operationId = item.sourceTaskId || item.id;
        const res = await selectFactoryWorkstation({
          taskId: this.form.operationId
        });
        let arr = res || [];
        this.form.list = arr.map((item) => {
          return {
            deviceId: item.extInfo?.assetId,
            deviceName: item.extInfo?.assetName,
            deviceCode: item.extInfo?.assetCode,
            workstationName: item.name,
            workstationId: item.id,
            model: item.modelType,
            deviceType: item.categoryLevelName,
            stationCycleTime: '',
            remark: '',
            priority: ''
            // deviceType: item.extInfo?.assetType,
          };
        });
      },
      stationBeatAdd(data) {
        data.forEach((item) => {
          this.form.list.push({
            deviceId: item.extInfo?.assetId,
            deviceName: item.extInfo?.assetName,
            deviceCode: item.extInfo?.assetCode,
            workstationName: item.name,
            workstationId: item.id,
            model: item.model,
            deviceType: item.deviceType,
            stationCycleTime: '',
            remark: '',
            priority: ''
          });
        });
      },
      save() {
        this.$refs.form.validate((valid) => {
          if (!this.form.list?.length) {
            this.$message.error('节拍信息不能为空');
            return;
          }
          if (valid) {
            let priorityList = this.form.list.map((item) => item.priority);

            if (new Set(priorityList).size !== priorityList.length) {
              this.$message.error('优先顺序不能重复');
              return;
            }
            this.loading = true;
            saveOrUpdate(this.form)
              .then((res) => {
                this.$message.success('操作成功');
                this.cancel();
                this.$emit('done');
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },

      //关闭弹窗
      cancel() {
        this.addOrEditDialogFlag = false;
        this.form = {
          ...defForm
        };
        this.form.list = [];
      }
    }
  };
</script>
<style scoped lang="scss">
  // :deep(.el-form-item--medium) {
  //   display: none;
  // }
</style>
