<template>
  <ele-modal :visible.sync="visible" :title="title" width="80vw" append-to-body>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="90px"
      class="create-form"
    >
      <el-row :gutter="15">
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="销售订单号:">
            <el-input clearable :maxlength="20" v-model="form.code" disabled />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="交付要求:">
            <DictSelection
              dictName="紧急程度"
              clearable
              v-model="form.deliveryRequirements"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="订单类型:">
            <el-select
              v-model="form.orderType"
              placeholder="请选择"
              @change="chooseType"
              style="width: 100%"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="按单按库:">
            <DictSelection
              dictName="按单按库"
              clearable
              v-model="form.orderLibraryType"
            >
            </DictSelection>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="客户名称:">
            <el-input
              clearable
              v-model="form.customerName"
              :disabled="form.orderType == 3"
            />
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="客户简称:">
            <el-input
              clearable
              v-model="form.simpleName"
              :disabled="form.orderType == 3"
            />
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="客户代号:">
            <el-input
              clearable
              v-model="form.serialNo"
              :disabled="form.orderType == 3"
            />
          </el-form-item>
        </el-col>

        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="业务员:">
            <el-input clearable v-model="form.salesman" />
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
          <el-form-item label="交付日期:" prop="deliveryTime">
            <el-date-picker
              :picker-options="pickerOptions"
              style="width: 100%"
              v-model="form.deliveryTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col v-bind="styleResponsive ? { lg: 18, md: 18 } : { span: 18 }">
          <el-form-item label="备注:">
            <el-input clearable v-model="form.notes" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-table :data="form.productInfoList" border height="40vh">
        <el-table-column label="序号" align="center" width="60">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="行号" align="center" prop="lineNumber">
        </el-table-column>
        <el-table-column label="产品名称" align="center" prop="productName">
        </el-table-column>
        <el-table-column label="物料编码" align="center" prop="productCode">
        </el-table-column>
        <el-table-column label="牌号" align="center" prop="brandNo">
        </el-table-column>
        <el-table-column label="型号" align="center" prop="model">
        </el-table-column>
        <el-table-column label="规格" align="center" prop="specification">
        </el-table-column>
        <el-table-column label="单重" align="center" prop="productUnitWeight">
        </el-table-column>
        <el-table-column label="重量单位" align="center" prop="weightUnit">
        </el-table-column>
        <el-table-column label="订单数量" align="center" prop="contractNum">
          <template slot-scope="scope">
            <el-form-item
              label-width="0px"
              :prop="'productInfoList.' + scope.$index + '.contractNum'"
              :rules="{
                required: true,
                message: '请输入订单数量',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model.number="scope.row.contractNum"
                size="small"
                oninput="value=value.replace(/[^\d]/g,'')"
                style="width: 100%"
                placeholder="输入数量"
                @input="inputNumber(scope.row, scope.$index)"
              ></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="计量单位" align="center" prop="measuringUnit">
          
        </el-table-column>
        <el-table-column
          label="模数"
          align="center"
          width="100"
          v-if="clientEnvironmentId == '4'"
        >
          <template slot-scope="scope">
            <div>
              <el-input
                style="width: 100%"
                size="small"
                v-model="scope.row.moCount"
                oninput="value=value.replace(/[^0-9.]/g,'')"
                @input="
                  tableHandleKeyUp(scope.row, scope.$index, $event, 'moCount')
                "
                placeholder="请输入"
              >
              </el-input>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          align="center"
          width="100"
          label="块数"
          v-if="clientEnvironmentId == '4'"
        >
          <template slot-scope="scope">
            <div>
              <el-input
                size="small"
                style="width: 100%"
               
                @input="
                  tableHandleKeyUp(
                    scope.row,
                    scope.$index,
                    $event,
                    'blockCount'
                  )
                "
                v-model="scope.row.blockCount"
                placeholder="请输入"
              ></el-input>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单重量" align="center" prop="productWeight">
          <template slot-scope="{ row }">
            <span>{{ row.productWeight ? row.productWeight : '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="70">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleDeleteItem(scope.$index)"
              v-if="!scope.row.id"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="add-product" @click="addEquipment">
        <i class="el-icon-circle-plus-outline"></i>
      </div>
    </el-form>
    <template v-slot:footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading">
        确定
      </el-button>
    </template>

    <!-- 选择产品 -->
    <EquipmentDialog
      ref="equipmentRefs"
      @choose="confirmChoose"
      :selectList="
        form.productInfoList.filter(
          (i) => !disabledList.find((p) => p.productCode === i.productCode)
        )
      "
    >
    </EquipmentDialog>
  </ele-modal>
</template>

<script>
import { getCode } from '@/api/codeManagement';
import EquipmentDialog from '../components/EquipmentDialog.vue';
import { createOrUpdate, getOrderDetail } from '@/api/saleOrder';
import { deepClone } from '@/utils';
import dayjs from 'dayjs';
import { multiply } from '@/utils/math';
export default {
  components: {
    EquipmentDialog
  },
  data() {
    return {
      visible: false,
      loading: false,
      disabledList: [], //已保存数据不做删除
      form: {
        productInfoList: [],
        deliveryRequirements: 1,
        orderType: 1,
        orderLibraryType: 2,
        deliveryTime: dayjs(
          new Date().getTime() + 3600 * 1000 * 24 * 10
        ).format('YYYY-MM-DD')
      },
      // 表单验证规则
      rules: {
        deliveryTime: [
          { required: true, message: '请选择交付日期', trigger: 'change' }
        ]
      },
      typeList: [
        { id: 1, label: '内销订单' },
        { id: 2, label: '外销订单' },
        { id: 3, label: '预制订单' }
      ],
      title: '创建订单',
      pickerOptions: {
        disabledDate: (time) => {
          // 禁用日期
          let nowData = new Date();
          nowData = new Date(nowData.setDate(nowData.getDate() - 1));
          return time < nowData;
        }
      }
    };
  },
  watch: {
    disabledList() {
      console.log(this.disabledList, 'disabledList');
    }
  },
  computed: {
    // 是否开启响应式布局
    styleResponsive() {
      return this.$store.state.theme.styleResponsive;
    },
    clientEnvironmentId() {
      return this.$store.state.user.info.clientEnvironmentId;
    }
  },
  created() {},
  methods: {
    open(row) {
      this.visible = true;
      if (row) {
        this.title = '修改订单';
        this.getDetail(row.code);
      } else {
        this.title = '创建订单';
        this.getSaleCode();
      }
    },
    getDetail(code) {
      getOrderDetail(code).then((res) => {
        this.disabledList = res.productInfoList;
        this.form = res;
      });
    },
    cancel() {
      this.form = {
        productInfoList: [],
        deliveryRequirements: 1,
        orderType: 1,
        orderLibraryType: 2,
        deliveryTime: dayjs(
          new Date().getTime() + 3600 * 1000 * 24 * 10
        ).format('YYYY-MM-DD')
      };
      this.$refs.form.clearValidate();
      this.visible = false;
    },

    // 表格：模数、数量(方)、块数输入框 输入事件
    tableHandleKeyUp(row, index, e, name) {
      let modelArr = row.specification.split('*');
      let modelLong = modelArr[0]; // model规格长度
      let modeWide = modelArr[1]; // model规格宽度
      let modeHight = modelArr[2].substr(0, modelArr[2].indexOf('cm')); // model规格高度
      modeHight = Number(modeHight);
      if (name === 'moCount') {
        // 模数
        row.moCount = e;
        // 计算块数的公式：
        // (一模6米长度 / model规格长度) * (一模1.2米宽度 / model规格宽度) = 每一模的块数
        // 每一模的块数*模数moCount = 总块数
        if (row.productName.includes('板材')) {
          row.blockCount =
            Math.floor(600 / modelLong) *
            Math.floor(120 / modeHight) *
            Math.floor(60 / modeWide) *
            row.moCount;
        } else if (row.productName.includes('砌块')) {
          let modelLongFixed = (600 / modelLong).toFixed(2);
          modelLongFixed = modelLongFixed.substring(
            0,
            modelLongFixed.length - 1
          );
          let modeWideFixed = (120 / modeWide).toFixed(2);
          modeWideFixed = modeWideFixed.substring(0, modeWideFixed.length - 1);
          let modeHightFixed = (60 / modeHight).toFixed(2);
          modeHightFixed = modeHightFixed.substring(
            0,
            modeHightFixed.length - 1
          );
          row.blockCount =
            Math.floor(modelLongFixed * modeWideFixed * modeHightFixed) *
            row.moCount;
        }

        row.contractNum =
          ((modelLong * modeWide * modeHight) / 1000000).toFixed(5) *
          row.blockCount;
      } else if (name === 'sum') {
        //方数
        row.contractNum = e;

        row.blockCount = Math.floor(
          e / ((modelLong * modeWide * modeHight) / 1000000)
        );
        if (row.productName.includes('板材')) {
          row.moCount = Math.ceil(
            row.blockCount /
              (Math.floor(600 / modelLong) *
                Math.floor(120 / modeHight) *
                Math.floor(60 / modeWide))
          );
        } else if (row.productName.includes('砌块')) {
          row.moCount = Math.ceil(
            row.blockCount /
              Math.floor(
                (600 / modelLong) * (120 / modeHight) * (60 / modeWide)
              )
          );
        }
      } else if (name === 'blockCount') {
        //块数
        row.blockCount = e;

        if (row.productName.includes('板材')) {
          row.moCount = Math.ceil(
            row.blockCount /
              (Math.floor(600 / modelLong) *
                Math.floor(120 / modeHight) *
                Math.floor(60 / modeWide))
          );
        } else if (row.productName.includes('砌块')) {
          row.moCount = Math.ceil(
            row.blockCount /
              Math.floor(
                (600 / modelLong) * (120 / modeHight) * (60 / modeWide)
              )
          );
        }
        row.contractNum =
          (Number(e) * modelLong * modeWide * modeHight) / 1000000;

      }
      row.contractNum = Number(row.contractNum.toFixed(5))

    },

    // 删除产品
    handleDeleteItem(index) {
      this.form.productInfoList.splice(index, 1);
      this.changeLineNumber();
    },
    addEquipment() {
      this.$refs.equipmentRefs.open();
    },
    /* 保存编辑 */
    save() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return false;
        }
        if (!this.form.productInfoList.length) {
          return this.$message.warning('产品列表不能为空！');
        }
        this.loading = true;
        createOrUpdate(this.form)
          .then((res) => {
            this.loading = false;
            this.$message.success('成功');
            this.cancel();
            this.$emit('refresh');
          })
          .catch((e) => {
            this.loading = false;
          });
      });
    },

    // 选择订单类型
    chooseType(val) {
      if (val == 2) {
        this.$set(this.form, 'orderLibraryType', 1);
      } else {
        this.$set(this.form, 'orderLibraryType', 2);
      }
      this.$set(this.form, 'customerName', '');
    },

    async getSaleCode() {
      const res = await getCode('sale_order');
      if (res) {
        this.$set(this.form, 'code', res);
      }
    },
    // 确定选择
    confirmChoose(list) {
      console.log('444', list);
      console.log(
        'this.form.productInfoList',
        deepClone(this.form.productInfoList)
      );
      list = list
        .filter(
          (i) =>
            !this.disabledList.find(
              (p) => p.productCode == i.code || p.productCode == i.productCode
            )
        )
        .map((item, index) => {
          if (item.productCode) {
            return item;
          } else {
            return {
              categoryId: item.id,
              productCode: item.code,
              productName: item.name,
              productUnitWeight: item.netWeight,
              weightUnit: item.weightUnit,
              model: item.modelType,
              specification: item.specification,
              brandNo: item.brandNum,
              measuringUnit:item.measuringUnit
            };
          }
        })
        .concat(this.disabledList);
      console.log('list', list);
      // 取出在弹窗中选中并且不在表格中的数据
      const result = list.filter(
        (i) =>
          this.form.productInfoList.findIndex(
            (p) => p.productCode === i.productCode
          ) === -1
      );
      console.log('result', result);
      // 取出在表格中并且不在弹窗中选中的数据 即取消选中的数据
      const del = this.form.productInfoList.filter(
        (i) => list.findIndex((p) => p.productCode === i.productCode) === -1
      );
      console.log('del', del);
      for (let i = this.form.productInfoList.length - 1; i >= 0; i--) {
        for (let j in del) {
          console.log(
            this.form.productInfoList[i].productCode,
            del[j].productCode
          );
          if (this.form.productInfoList[i].productCode === del[j].productCode) {
            this.form.productInfoList.splice(i, 1);
            break;
          }
        }
      }

      this.form.productInfoList = this.form.productInfoList.concat(result);
      this.changeLineNumber();
    },

    changeLineNumber() {
      this.form.productInfoList.map((item, index) => {
        item.lineNumber = 10 * (index + 1);
      });
    },

    inputNumber(row, index) {
      const pos = this.form.productInfoList;
      if (pos[index].productUnitWeight) {
        const number = multiply(row.contractNum, row.productUnitWeight);

        this.$set(pos[index], 'productWeight', number);
      }
      if(this.clientEnvironmentId==4){
        this.tableHandleKeyUp(row, '', row.contractNum, 'sum');

      }

    }
  }
};
</script>
<style lang="scss" scoped>
.basic-details-title {
  margin: 10px 0;
}

.add-product {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 30px;
  color: #1890ff;
  margin: 10px 0;
  cursor: pointer;
}

.create-form .el-form-item {
  margin-bottom: 15px !important;
}
</style>
