<!-- 搜索表单 -->
<template>
  <el-form
    label-width="90px"
    class="ele-form-search"
    @keyup.enter.native="search"
    @submit.native.prevent
  >
    <el-row :gutter="15">
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="关键字:">-->
      <!--          <el-input-->
      <!--            v-model="where.keyWord"-->
      <!--            size="mini"-->
      <!--            placeholder="请输入"-->
      <!--          ></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="销售订单号:">-->
      <!--          <el-input-->
      <!--            v-model="where.code"-->
      <!--            size="mini"-->
      <!--            placeholder="请输入"-->
      <!--          ></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="产品编码:">-->
      <!--          <el-input-->
      <!--            v-model="where.productCode"-->
      <!--            size="mini"-->
      <!--            placeholder="请输入"-->
      <!--          ></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="行号:">-->
      <!--          <el-input-->
      <!--            v-model="where.lineNumber"-->
      <!--            size="mini"-->
      <!--            placeholder="请输入"-->
      <!--          ></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="牌号:">-->
      <!--          <el-input-->
      <!--            v-model="where.brandNo"-->
      <!--            size="mini"-->
      <!--            placeholder="请输入"-->
      <!--          ></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="型号:">-->
      <!--          <el-input-->
      <!--            v-model="where.model"-->
      <!--            size="mini"-->
      <!--            placeholder="请输入"-->
      <!--          ></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="订单来源:">-->
      <!--          <DictSelection-->
      <!--            dictName="订单来源"-->
      <!--            size="mini"-->
      <!--            clearable-->
      <!--            v-model="where.orderSource"-->
      <!--          >-->
      <!--          </DictSelection>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="客户名称:">-->
      <!--          <el-input-->
      <!--            v-model="where.customerName"-->
      <!--            size="mini"-->
      <!--            placeholder="请输入"-->
      <!--          ></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="订单类型:">-->
      <!--          <DictSelection-->
      <!--            dictName="订单类型"-->
      <!--            clearable-->
      <!--            size="mini"-->
      <!--            v-model="where.orderType"-->
      <!--          >-->
      <!--          </DictSelection>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <el-col v-bind="styleResponsive ? { lg: 4, md: 12 } : { span: 4 }">
        <el-form-item label="生产状态:">
          <el-select
            v-model="where.proStu"
            placeholder="请选择"
            class="w100"
            size="mini"
          >
            <el-option
              v-if="activeName == 'first'"
              v-for="item in awaitProcuct"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
            <el-option
              v-if="activeName == 'three'"
              v-for="item in treatProcuct"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>

            <el-option
              v-if="activeName == 'second'"
              v-for="item in alreadyProcuct"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col v-bind="styleResponsive ? { lg: 4, md: 12 } : { span: 4 }">
        <el-form-item label="订单类型:">
          <el-select
            v-model="where.orderType"
            placeholder="请选择"
            class="w100"
            size="mini"
          >
            <el-option
              v-for="item in orderList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="业务员:">-->
      <!--          <el-input-->
      <!--            v-model="where.salesman"-->
      <!--            size="mini"-->
      <!--            placeholder="请输入"-->
      <!--          ></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->

      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">-->
      <!--        <el-form-item label="产品名称:">-->
      <!--          <el-input-->
      <!--            v-model="where.productName"-->
      <!--            size="mini"-->
      <!--            placeholder="请输入"-->
      <!--          ></el-input>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->

      <el-col v-bind="styleResponsive ? { lg: 6, md: 12 } : { span: 6 }">
        <el-form-item label="交货日期:">
          <el-date-picker
            style="width: 100%"
            v-model="time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="mini"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
      <!--      <el-col v-bind="styleResponsive ? { lg: 6, md: 6 } : { span: 6 }">-->
      <!--        <el-form-item label="组织机构:">-->
      <!--          <auth-selection-->
      <!--            data-type="Array"-->
      <!--            size="mini"-->
      <!--            v-model="where.deptIds"-->
      <!--            style="width: 100%"-->
      <!--          ></auth-selection>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <el-col v-bind="styleResponsive ? { lg: 3, md: 12 } : { span: 3 }">
        <el-form-item label-width="0">
          <el-input
            size="mini"
            clearable
            v-model="where.searchInfo"
            placeholder="请输入查询信息"
          />
        </el-form-item>
      </el-col>
      <el-col v-bind="styleResponsive ? { lg: 4, md: 6 } : { span: 4 }">
        <div class="ele-form-actions">
          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              展开<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu>
              <div class="searchExpend">
                <el-row>
                  <el-form-item label="关键字:" label-width="80px">
                    <el-input
                      v-model="where.keyWord"
                      size="mini"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="销售订单号:">
                    <el-input
                      v-model="where.code"
                      size="mini"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="产品编码:">
                    <el-input
                      v-model="where.productCode"
                      size="mini"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="订单来源:">
                    <DictSelection
                      dictName="订单来源"
                      size="mini"
                      clearable
                      v-model="where.orderSource"
                    >
                    </DictSelection>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="客户名称:">
                    <el-input
                      v-model="where.customerName"
                      size="mini"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="销售类型:">
                    <DictSelection
                      dictName="订单类型"
                      clearable
                      size="mini"
                      v-model="where.saleType"
                    >
                    </DictSelection>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="业务员:">
                    <el-input
                      v-model="where.salesman"
                      size="mini"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="产品名称:">
                    <el-input
                      v-model="where.productName"
                      size="mini"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-row>

                <!-- <el-row>
                  <el-form-item label="组织机构:">
                    <auth-selection
                      data-type="Array"
                      size="mini"
                      v-model="where.deptIds"
                      style="width: 100%"
                    ></auth-selection>
                  </el-form-item>
                </el-row> -->

                <el-row>
                  <el-form-item label="按单按库:">
                    <el-select
                      v-model="where.orderLibraryType"
                      placeholder="请选择"
                      class="w100"
                      size="mini"
                    >
                      <el-option
                        v-for="item in orderTypeList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-row>
              </div>
            </el-dropdown-menu>
          </el-dropdown>

          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            class="ele-btn-icon"
            @click="search"
          >
            查询
          </el-button>
          <el-button
            @click="reset"
            size="mini"
            icon="el-icon-refresh-left"
            type="primary"
            >重置</el-button
          >
        </div>
      </el-col>
      <el-col v-bind="styleResponsive ? { lg: 24, md: 24 } : { span: 24 }">
        <el-form-item label-width="0px">
          <div class="btn-wrapper">
            <!-- <el-button
              @click="payBudget"
              size="mini"
              type="danger"
            >
              交期预估</el-button
            > -->
            <!-- <el-button @click="homogeneityInspect" size="mini" type="success">
              齐套性检查</el-button
            > -->
            <el-dropdown
              trigger="click"
              @command="homogeneityInspect"
              v-if="$hasPermission('aps:saleOrder:homogeneityInspect')"
            >
              <el-button size="mini" type="success">齐套性检查</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="1"> 自制件 </el-dropdown-item>
                <el-dropdown-item command="2"> 采购件 </el-dropdown-item>
                <el-dropdown-item command="1"> 受托件 </el-dropdown-item>
                <!-- <el-dropdown-item command="3"> 外协件 </el-dropdown-item> -->
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              @click="goProduct"
              size="mini"
              v-if="
                activeName != 'second' &&
                $hasPermission('aps:salesorder:update')
              "
            >
              转生产计划</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="orderRefresh"
              :loading="loading"
              >订单刷新</el-button
            >
            <el-button
              type="success"
              size="mini"
              @click="toCreate"
              v-if="
                activeName == 'first' && $hasPermission('aps:salesorder:save')
              "
              >创建订单</el-button
            >

            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              v-if="
                activeName == 'first' && $hasPermission('aps:saleOrder:upload')
              "
              :http-request="uploadFile"
              :before-upload="beforeUpload"
              :on-change="handleChange"
              ref="uploadFile"
            >
              <el-button type="warning" size="mini">批量导入</el-button>
            </el-upload>
            <el-button
              type="info"
              size="mini"
              @click="
                importTemplate(
                  '/aps/salesorder/importTemplate',
                  '销售订单模板.xlsx'
                )
              "
              v-if="$hasPermission('aps:salesorder:download')"
            >
              下载模板
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="batchDelete"
              v-if="activeName == 'first'"
              >批量删除</el-button
            >

            <el-button
              type="danger"
              size="mini"
              @click="synchronous"
              v-if="activeName == 'first' && clientEnvironmentId == 2"
              >同步数据</el-button
            >
            <el-button
              v-if="$hasPermission('aps:salesorder:export')"
              :disabled="selection.length < 1"
              type="primary"
              size="mini"
              @click="handlePrint"
              >打印</el-button
            >
          </div>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 导入异常 -->
    <import-exception ref="importDialog"> </import-exception>
    <!-- 创建订单 -->
    <create-order ref="createDialog" @refresh="search"> </create-order>
    <!-- 订单组合 -->
    <group-order ref="groupDialog"> </group-order>

    <printTemplateSaleOrder
      :groupName="groupName"
      ref="printTemplateSaleOrderRef"
    ></printTemplateSaleOrder>
  </el-form>
</template>

<script>
  import {
    findBomCategoryByCategoryId,
    listBomType
  } from '@/api/productionPlan/index';
  import ImportException from '../components/import-exception.vue';
  import CreateOrder from '../components/create-order.vue';
  import GroupOrder from '../components/group-order.vue';
  import { importFile } from '@/api/saleOrder';
  import { importTemplate } from '@/api/aps/presalesorder';
  import {
    pullSalesOrder,
    deleteOrder,
    synchronousDataByJDY
  } from '@/api/saleOrder';
  import printTemplateSaleOrder from './printTemplateSaleOrder.vue';
  export default {
    props: {
      selection: Array,
      activeName: String
    },
    components: {
      ImportException,
      CreateOrder,
      GroupOrder,
      printTemplateSaleOrder
    },
    data() {
      // 默认表单数据
      const defaultWhere = {
        keyWord: '',
        code: '',
        productCode: '',
        customerName: '',
        lineNumber: '',
        model: '',
        brandNo: '',
        orderSource: 0,
        saleType: 0,
        proStu: '',
        orderLibraryType: 0,
        salesman: '',
        productName: ''
      };
      return {
        importTemplate,
        // 表单数据
        defaultWhere,
        where: { ...defaultWhere },
        time: [],
        fileList: [],
        awaitProcuct: [{ value: 1, label: '待排产' }],
        treatProcuct: [{ value: 0, label: '未排完' }],
        alreadyProcuct: [
          { value: 0, label: '所有状态' },
          { value: 2, label: '待发布' },
          { value: 3, label: '发布失败' },
          { value: 4, label: '待生产' },
          { value: 5, label: '生产中' },
          { value: 6, label: '已完成' },
          { value: 7, label: '已延期' }
        ],
        orderTypeList: [
          { value: 0, label: '所有' },
          { value: 1, label: '按单' },
          { value: 2, label: '按库' }
        ],

        orderList: [
          {
            value: 0,
            label: '库存性订单'
          },
          {
            value: 1,
            label: '生产性订单'
          },
          {
            value: 2,
            label: '无客户生产性订单'
          },
          {
            value: 4,
            label: '不定向订单'
          }
        ],
        loading: false
      };
    },
    computed: {
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      },

      clientEnvironmentId() {
        return this.$store.state.user.info.clientEnvironmentId;
      }
    },
    watch: {
      activeName: {
        handler() {
          if (this.activeName == 'first') {
            this.where.proStu = 1;
          } else {
            this.where.proStu = 0;
          }

          this.reset();
        },
        immediate: true
      }
    },
    created() {},
    methods: {
      /* 搜索 */
      search() {
        if (this.time.length) {
          this.where.startTime = this.time[0];
          this.where.endTime = this.time[1];
        }
        this.$emit('search', this.where);
      },
      /*  重置 */
      reset() {
        this.time = [];
        this.where = { ...this.defaultWhere };
        if (this.activeName == 'first') {
          this.where.proStu = 1;
        } else {
          this.where.proStu = 0;
        }
        this.search();
      },
      toImport() {
        this.$refs.importDialog.open();
      },
      toCreate() {
        this.$refs.createDialog.open();
      },
      toGroup() {
        this.$refs.groupDialog.open();
      },
      async goProduct() {
        console.log(this.selection, 'this.selection 33');
        if (!this.selection.length) {
          return this.$message.warning('请先勾选一个或多个订单！');
        }
        const productCode = this.selection[0].productCode;
        const orderType = this.selection[0].orderType;
        const produceRoutingId = this.selection[0].produceRoutingId;
        const measuringUnit = this.selection[0].measuringUnit;
        const factoriesId = this.selection[0].factoriesId;
        const factoriesIdName = this.selection[0].factoriesIdName;
        const bomCategoryId = this.selection[0].bomCategoryId;
        const saleType = this.selection[0].saleType;
        let produceType = this.selection[0].produceType[0];
        // if(!factoriesId){
        //   this.$message.warning('工厂未选择！');
        //   return;
        // }

        for (var i = 0; i < this.selection.length; i++) {
          if (productCode != this.selection[i].productCode) {
            return this.$message.warning('产品编码不一致！');
          }
          if (orderType != this.selection[i].orderType) {
            return this.$message.warning('订单类型不一致！');
          }
          if (saleType != this.selection[i].saleType) {
            return this.$message.warning('销售类型不一致！');
          }
          if (produceRoutingId != this.selection[i].produceRoutingId) {
            return this.$message.warning('工艺路线不一致！');
          }
          if (measuringUnit != this.selection[i].measuringUnit) {
            return this.$message.warning('计量单位不一致！');
          }
          if (factoriesId != this.selection[i].factoriesId) {
            return this.$message.warning('所属工厂不一致！');
          }
        }
        const list = [];
        let startTime = '';
        let endTime = '';
        this.selection.map((item) => {
          if (!startTime) {
            startTime = item.releaseTime;
          } else {
            startTime =
              this.compareTimes(startTime, item.releaseTime) == 1
                ? item.releaseTime
                : startTime;
          }
          if (!endTime) {
            endTime = item.deliveryTime;
          } else {
            endTime =
              this.compareTimes(endTime, item.deliveryTime) == 2
                ? item.deliveryTime
                : endTime;
          }
          list.push(item.id);
        });
        if (produceRoutingId && !bomCategoryId) {
          produceType = '';
        }
        console.log(this.selection, 'this.selection 3333');
        let categoryId = this.selection[0].categoryId;
        let params = { categoryId: categoryId };
        const res = await listBomType(params);
        console.log(res, 'res 000');
        let bomMap = {
          1: { code: 1, name: 'PBOM' },
          2: { code: 2, name: 'MBOM' },
          3: { code: 3, name: 'ABOM' }
        };
        let arr = [];
        res.map((item) => {
          if (bomMap[item.bomType]) {
            arr.push(bomMap[item.bomType]);
            delete bomMap[item.bomType];
          }
        });
        if (arr.length) {
          let obj = arr.find((el) => el.code == produceType);
          produceType = obj
            ? produceType
            : arr.filter((el) => el.code != 1)?.[0]?.code;
        }
        if (arr.length == 0) {
          produceType = '';
        }
        console.log(produceType, 'produceType');
        console.log(arr, 'arr 222');
        // const res = await findBomCategoryByCategoryId(categoryId);
        // let arr = [];
        // if (res.length > 0) {
        //   let obj = res.find((item) => item.id === bomCategoryId);
        //   produceType = obj ? obj.bomType : produceType;
        //   let listMap = {
        //     1: { code: 1, name: 'PBOM' },
        //     2: { code: 2, name: 'MBOM' },
        //     3: { code: 3, name: 'ABOM' }
        //   };
        //   res.forEach((el) => {
        //     if (listMap[el.bomType]) {
        //       arr.push(listMap[el.bomType]);
        //       delete listMap[el.bomType];
        //     }
        //   });
        // }
        this.$router
          .push({
            path: '/saleOrder/salesToProduction',
            query: {
              orderType,
              selection: JSON.stringify(list),
              produceRoutingId: produceRoutingId,
              produceRoutingName: this.selection[0].produceRoutingName,
              categoryId: this.selection[0].categoryId,
              factoriesId: factoriesId,
              factoriesIdName: factoriesIdName,
              bomCategoryId: bomCategoryId,
              produceType: produceType,
              startTime,
              endTime,
              producedList: JSON.stringify(arr)
            }
          })
          .catch((error) => {
            // 忽略重复导航错误
            if (error.name !== 'NavigationDuplicated') {
              console.error('路由跳转失败:', error);
            }
          });
      },
      // 比较时间大小
      compareTimes(timeStr1, timeStr2) {
        // 将时间字符串转换为Date对象
        // 注意：需要将空格替换为'T'以符合ISO格式，或者直接按格式解析
        const date1 = new Date(timeStr1.replace(' ', 'T'));
        const date2 = new Date(timeStr2.replace(' ', 'T'));

        if (date1 > date2) {
          return 1;
        } else {
          return 2;
        }
      },
      // 刷新订单
      orderRefresh() {
        this.loading = true;
        pullSalesOrder()
          .then((res) => {
            this.$message.success('刷新成功！');
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      },

      // 点击批量删除
      batchDelete() {
        if (!this.selection.length) {
          return this.$message.warning('请先勾选一个或多个订单！');
        }
        let ids = [];
        this.selection.map((item) => {
          ids.push(item.id);
        });
        this.$confirm('此操作将永久删除所选择的订单, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            deleteOrder(ids).then((res) => {
              this.$message.success(res);
              this.search();
            });
          })
          .catch(() => {});
      },

      handleChange(file, fileList) {
        this.fileList = fileList;
        console.log(fileList);
      },

      //上传限制
      beforeUpload(file) {
        const isLt10M = file.size / 1024 / 1024 < 10;
        if (!isLt10M) {
          this.$message.error('上传文件大小不能超过 10MB!');
        }
        return isLt10M;
      },
      //文件上传
      uploadFile(param) {
        let fd = new FormData();
        this.fileList.forEach((item) => {
          fd.append('importExcel', item.raw);
        });
        importFile(fd)
          .then((res) => {
            this.$emit('search', this.where);
            this.$refs.uploadFile.clearFiles();
          })
          .catch((data) => {
            if (data.code != -1) {
              this.$message.error(data.message);
            }
          })
          .finally(() => {
            this.$refs.uploadFile.clearFiles();
          });
      },

      synchronous() {
        synchronousDataByJDY().then((res) => {
          this.$message.success('同步成功！');
          this.reset();
        });
      },
      // payBudget() {},
      homogeneityInspect(val) {
        console.log(val, 'val');
        this.$emit('check', val);
      },
      handlePrint() {
        console.log(this.selection[0]);
        if (this.selection.length > 1)
          return this.$message.warning('请选择一条');
        this.$refs.printTemplateSaleOrderRef.open(this.selection[0]);
      }
    }
  };
</script>
<style lang="scss" scoped>
  .ele-form-actions {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding-top: 4.5px;
  }

  .btn-wrapper {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .avatar-uploader {
    display: inline-block;
    margin: 0 10px;
  }

  .button-link {
    color: #fff;
  }
  .searchExpend {
    padding: 20px 50px 0 30px;
  }
</style>
