<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="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;
    }
  },
  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;
    },
    // 删除产品
    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,
              brandNo: item.brandNum
            };
          }
        })
        .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
        );
      }
    }
  }
};
</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>
