<template>
  <div class="pageIndexClass">
    <div class="content">
      <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" :selectConfig="selectConfig"
               :statConfig="statConfig" :onMoreSearch="false" @moreSearch="clickMoreSearch" highlight-current-row :action-list="[
          {
            text: '新建',
            action: () => newContract(),
          },
        ]" @get-list="getList">
        <template #code="{ item }">
          <div style="width: 100%">
            <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="openDetails(item)">{{ item.code }}</a>
          </div>
        </template>

        <template #isSettled="{ item }">
          <div>
            <span style="padding: 4px" :class="[item.isSettled == 1 ? 'active' : '']">
              {{
                proxy.dictValueLabel(item.isSettled, isSettled)
              }}</span>
          </div>
        </template>

        <template #contractType="{ item }">
          <div style="width: 100%">
            <span>
              {{ dictKeyValue(item.contractType, contractType) }}
            </span>
          </div>
        </template>

        <template #produceStatus="{ item }">
          <div style="width: 100%">
            <span v-if="item.produceStatus==0 || item.produceStatus" :class="item.produceStatus==10?'tag-active':'tag-active-1'">
              {{ dictValueLabel(item.produceStatus, produceStatusData) }}</span>
          </div>
        </template>

        <template #amount="{ item }">
          <div>
            <span style="padding-right: 4px">{{ item.currency }}</span>
            <span>{{ moneyFormat(item.amount, 2) }}</span>
          </div>
        </template>
        <template #buyCorporationName="{ item }">
          <div style="width: 100%">
            <a style="color: #409eff; cursor: pointer" @click="clickCorporationName(item)">{{ item.buyCorporationName }}</a>
          </div>
        </template>

        <template #product="{item}">
          <div style="width: 100%">
            <el-popover placement="top-start" :width="400" trigger="hover" @show="onShowProductData(item)">
              <div style="display:flex;margin-bottom:20px;align-items:center" v-for="i in  productData" :key="i.id">
                <div style="width:60px">
                  <img :src="i.productImgUrl" alt="" class="pic" @click="handleClickFile(i.productImgUrl)">
                </div>
                <div style="width:calc(100% - 60px)">
                  <div>产品编码：{{i.productCode}}</div>
                  <div>产品名称：{{i.productName}}</div>
                  <div>产品尺寸：{{i.productLength}}cm*{{i.productWidth}}cm*{{i.productHeight}}cm</div>
                  <div>产品颜色：{{i.productColor}}</div>
                  <div>产品数量：{{i.quantity}}</div>
                </div>
              </div>
              <template #reference>
                <div style="display:flex;height:65px;position:relative;top:15px">
                  <div v-for="(product,index) in item.contractProductList" :key="product.id" style="margin-right:10px;position:relative;">
                    <el-badge :value="product.quantity" :min="0" :max="999999" v-if="index<3">
                      <img :src="product.productImgUrl" class="pic" @click="handleClickFile(product.productImgUrl)">
                    </el-badge>
                    <div v-if="index==3" class="more">
                      共{{item.contractProductList.length}}款
                    </div>
                  </div>
                </div>
              </template>
            </el-popover>
          </div>
        </template>

        <template #deliveryTime="{ item }">
          <div style="width: 100%;display:flex;align-items:center">
            <el-icon v-if="item.orderDistributeStatus==1 && item.deliveryTime" :size="16" style="cursor:pointer;margin-right: 8px;" color="#409EFF"
                     @click="clickDistributeProduction(item)">
              <Edit />
            </el-icon>
            <div v-if="item.deliveryTime">
              {{item.deliveryTime.slice(0,10)}}
            </div>
          </div>
        </template>

        <template #prodTag="{ item }">
          <div style="width: 100%;display:flex;align-items:center">
            <el-icon :size="16" style="cursor:pointer;margin-right: 8px;" color="#409EFF" @click="handleEditTag(item)">
              <Edit />
            </el-icon>
            <el-popover placement="top-start" :width="300" trigger="hover">
              <div>
                备注：{{item.prodRemark}}
              </div>
              <template #reference>
                <div style="width:100%;display:inline-block">
                  <el-tag style="margin-right: 8px" type="success" v-for="(tag, index) in item.prodTags" closable :key="index"
                          @close="prodTagClose(index, item)">
                    {{ dictKeyValue(tag, contractTag) }}
                  </el-tag>
                </div>

              </template>
            </el-popover>
          </div>
        </template>

        <template #tags="{ item }">
          <div style="width: 100%">
            <el-tag style="margin-right: 8px" type="success" v-for="(tag, index) in item.tags" closable :key="index" @close="tagClose(tag, item)">
              {{ dictValueLabel(tag, customerTag) }}
            </el-tag>
            <template v-if="item.tags.length !== customerTag.length">
              <el-select v-if="item.addTagShow" v-model="addTag" style="width: 100%" @change="
                  (val) => {
                    return changeTag(val, item);
                  }
                ">
                <el-option v-for="tag in customerTag" :key="tag.value" :label="tag.label" :value="tag.value"
                           :disabled="judgeTagSelect(item.tags, tag.value)" />
              </el-select>
              <el-tag style="cursor: pointer" type="success" @click="showSelect(item)" v-else>
                +
              </el-tag>
            </template>
          </div>
        </template>
        <template #advanceRatio="{ item }">
          <div>
            <span>{{ moneyFormat(item.advanceRatio, 2) }}%</span>
          </div>
        </template>

        <template #scale="{ item }">
          <div>
            {{ computeScale(item) }}
          </div>
        </template>
      </byTable>
    </div>

    <el-dialog title="打印" v-if="openPrint" v-model="openPrint" width="920">
      <ContractPDFOne :rowData="rowData"></ContractPDFOne>
      <!-- <ContractPDFOneNew :rowData="rowData" ref="PdfDom"></ContractPDFOneNew> -->
      <!-- <template #footer>
        <el-button @click="openPrint = false" size="default">取消</el-button>
        <el-button type="primary" v-print="printObj" size="default">打印</el-button>
        <el-button type="primary" @click="clickDownload()" size="default">下载PDF</el-button>
        <el-button type="primary" @click="exportExcel()" size="default">导出Excel</el-button>
      </template> -->
    </el-dialog>

    <el-dialog title="交接单" v-if="openHandoverSlip" v-model="openHandoverSlip" width="600">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="handoverSlipForm">
        <template #file>
          <div style="width: 100%">
            <el-upload v-model:fileList="handoverSlipForm.fileList" :action="uploadUrl" :data="uploadData" multiple :before-upload="uploadFile"
                       :on-success="handleSuccess" :on-preview="onPreviewFile">
              <el-button type="primary" plain>选择</el-button>
            </el-upload>
          </div>
        </template>
        <template #indication>
          <div style="width: 100%">
            <el-upload v-model:fileList="handoverSlipForm.packageFileList" :action="uploadUrl" :data="indicationUploadData" multiple
                       :before-upload="indicationUploadFile" :on-success="handleSuccess" :on-preview="onPreviewFile">
              <el-button type="primary" plain>选择</el-button>
            </el-upload>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openHandoverSlip = false" size="default">关 闭</el-button>
        <el-button type="primary" @click="submitHandoverSlip()" size="default">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="合同详情" v-if="openDetailsDialog" v-model="openDetailsDialog" width="1100">
      <ContractDetails :contractId="currentContractId"></ContractDetails>
    </el-dialog>

    <el-dialog :title="`售后记录`" v-if="openRecords" v-model="openRecords" width="600">
      <div style="padding-left: 50px; margin-bottom: 20px">
        <el-button type="primary" plain @click="handleClickAddRecord()">添加记录</el-button>
      </div>
      <el-timeline>
        <el-timeline-item v-for="(activity, index) in recordsData" :key="index">
          <div style="
              width: 100%;
              display: flex;
              justify-content: space-between;
              color: #bfb9b9;
            ">
            <div>售后时间：{{ activity.documentaryTime }}</div>
            <div>{{ activity.userName }}</div>
          </div>
          <div style="width: 100%; margin-top: 8px">
            售后记录：{{ activity.documentaryRemark }}
          </div>
          <div style="width: 100%; margin-top: 8px" v-if="activity.fileList && activity.fileList.length > 0">
            <div v-for="(item, index) in activity.fileList" :key="index">
              <div style="cursor: pointer; color: #409eff" @click="openFile(item)">
                {{ item.fileName }}
              </div>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>

      <template #footer>
        <el-button @click="openRecords = false" size="default">关 闭</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="`添加售后记录`" v-if="openAddRecords" v-model="openAddRecords" width="600">
      <byForm :formConfig="recordsFormConfig" :formOption="formOption" v-model="formData.recordsFormData" :rules="recordsRules" ref="recordsForm"
              v-loading="formLoading">
        <template #file>
          <div style="width: 100%">
            <el-upload v-model:fileList="formData.recordsFormData.fileList" :action="uploadUrl" :data="uploadData" multiple
                       :before-upload="uploadFile" :on-success="handleSuccess" :on-preview="onPreviewFile">
              <el-button type="primary" plain>选择</el-button>
            </el-upload>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openAddRecords = false" size="default">关 闭</el-button>
        <el-button type="primary" @click="submitRecords()" size="default">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="'高级检索'" v-model="moreSearchDialog" width="500px" destroy-on-close>
      <byForm :formConfig="formSearchConfig" :formOption="formOption" v-model="sourceList.pagination">
      </byForm>
      <template #footer>
        <el-button @click="moreSearchReset" size="default">重置</el-button>
        <el-button @click="moreSearchQuery" type="primary" size="default" v-debounce>搜索</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="'生产'" v-model="productionDialog" width="700px" destroy-on-close>
      <byForm :formConfig="productionFormConfig" :formOption="formOption" v-model="formData.data" :rules="productionRules" ref="productionFormDom"
              v-loading="formLoading">

      </byForm>
      <template #footer>
        <el-button @click="productionDialog =false" size="default">取 消</el-button>
        <el-button @click="submitProduction" type="primary" size="default" v-debounce>下 发</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="'生产指示'" v-model="tagDialog" width="700px" destroy-on-close>
      <byForm :formConfig="tagFormConfig" :formOption="formOption" v-model="formData.tagData" :rules="tagRules" ref="tagFormDom"
              v-loading="formLoading">
      </byForm>
      <template #footer>
        <el-button @click="tagDialog =false" size="default" v-debounce>取 消</el-button>
        <el-button @click="submitTag" type="primary" size="default" v-debounce>提 交</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { computed, ref, watch } from "vue";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";
import ContractDetails from "@/components/contractCom/contractDetails.vue";
import ContractPDFOne from "@/components/PDF/contractPDFOne.vue";
import ContractPDFOneNew from "@/components/PDF/contractPDFOneNew.vue";
import $bus from "@/bus/index.js";
import moment from "moment";
const route = useRoute();
const contractTag = computed(
  () => proxy.useUserStore().allDict["contract_prod_tag"]
);
const { proxy } = getCurrentInstance();
const accountCurrency = ref([]);
const tradeMethods = ref([]);
const corporationList = ref([]);
const customerList = ref([]);
const userList = ref([]);
const companyData = ref([]);
const isSettled = ref([
  {
    label: "已结清",
    value: "1",
  },
  {
    label: "未结清",
    value: "0",
  },
]);

const shippingMethod = ref([]);
const customerTag = ref([]);
const openDetailsDialog = ref(false);
const produceStatusData = ref([
  {
    label: "未开始",
    value: "0",
  },
  {
    label: "生产中",
    value: "1",
  },
  {
    label: "生产完成",
    value: "2",
  },
  {
    label: "出库中",
    value: "5",
  },
  {
    label: "已出库",
    value: "10",
  },
  {
    label: "作废",
    value: "99",
  },
]);
const status = ref([
  {
    label: "草稿",
    value: 0,
  },
  {
    label: "审批中",
    value: 10,
  },
  {
    label: "驳回",
    value: 20,
  },
  {
    label: "审批通过",
    value: 30,
  },
  {
    label: "变更中",
    value: 60,
  },
  {
    label: "已变更",
    value: 70,
  },
  {
    label: "作废",
    value: 88,
  },
  {
    label: "终止",
    value: 99,
  },
]);

const contractType = ref([
  {
    dictKey: "3",
    dictValue: "打样订单",
  },
  {
    dictKey: "2",
    dictValue: "内销订单",
  },
  {
    dictKey: "1",
    dictValue: "外贸订单(退税)",
  },
  {
    dictKey: "4",
    dictValue: "外贸订单(不退税)",
  },
]);

const belongTypeData = ref([
  {
    dictKey: "1",
    dictValue: "归属工厂",
  },
  {
    dictKey: "2",
    dictValue: "归属业务",
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    status: "",
    companyId: "",
    userId: "",
    isSettled: "",
    beginTime: "",
    endTime: "",
    deliveryTimeSta: "",
    deliveryTimeEnd: "",
    type: "",
    produceStatus: "",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "业务公司",
      prop: "ofCompanyId",
      data: proxy.useUserStore().allDict["list_company_data"],
    },
    {
      label: "订单类型",
      prop: "contractType",
      data: contractType.value,
    },
    {
      label: "审批状态",
      prop: "status",
      data: status.value,
    },
    {
      label: "工厂",
      prop: "companyId",
      data: companyData.value,
    },
    // {
    //   label: "生产状态",
    //   prop: "produceStatus",
    //   data: produceStatusData.value,
    // },
    {
      label: "业务员",
      prop: "userId",
      data: userList.value,
    },
    {
      label: "是否已结清",
      prop: "isSettled",
      data: isSettled.value,
    },
    {
      type: "time",
      label: "创建时间",
      placeholder: "开始日期",
      prop: "beginTime",
      placeholderOne: "结束日期",
      propOne: "endTime",
    },
    {
      type: "time",
      label: "交期",
      placeholder: "开始日期",
      prop: "deliveryTimeSta",
      placeholderOne: "结束日期",
      propOne: "deliveryTimeEnd",
    },
  ];
});
const headerData = ref({});
const statConfig = computed(() => [
  // {
  //   label: "统计",
  //   data: [
  //     //一个卡牌多数据配置
  //     {
  //       label: "订单统计（CNY）",
  //       type: 2,
  //       data: [
  //         {
  //           label: "订单数",
  //           num: headerData.value.count,
  //           color: "#C280FF",
  //         },
  //         {
  //           label: "客户数",
  //           num: headerData.value.customerCount,
  //           color: "#C280FF",
  //         },
  //         {
  //           label: "订单金额",
  //           num: proxy.moneyFormat(headerData.value.sumAmount, 2),
  //           color: "#C280FF",
  //         },
  //       ],
  //     },
  //     {
  //       label: "款项统计（CNY）",
  //       type: 3,
  //       data: [
  //         {
  //           label: "已收款",
  //           num: proxy.moneyFormat(headerData.value.sumClaimMoney, 2),
  //           color: "#FF9315",
  //         },
  //         {
  //           label: "待收款",
  //           num: proxy.moneyFormat(headerData.value.sumClaimMoneyOne, 2),
  //           color: "#FF9315",
  //         },
  //       ],
  //     },
  //   ],
  // },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "业务公司",
        prop: "ofCompanyName",
        width: 110,
      },
    },
    {
      attrs: {
        label: "业务部门",
        prop: "deptName",
        width: 110,
      },
    },
    {
      attrs: {
        label: "订单类型",
        slot: "contractType",
        width: 110,
      },
    },
    {
      attrs: {
        label: "合同号",
        slot: "code",
        width: 140,
      },
    },
    {
      attrs: {
        label: "工厂",
        prop: "companyName",
        width: 120,
      },
    },
    {
      attrs: {
        label: "订单归属",
        prop: "belongType",
        width: 80,
      },
      render(val) {
        return proxy.dictKeyValue(val, belongTypeData.value);
      },
    },
    {
      attrs: {
        label: "生产状态",
        // prop: "produceStatus",
        slot: "produceStatus",
        width: 100,
      },
      // render(val) {
      //   return proxy.dictValueLabel(val, produceStatusData.value);
      // },
    },
    // {
    //   attrs: {
    //     label: "销售部门",
    //     prop: "deptName",
    //     width: 120,
    //   },
    // },
    {
      attrs: {
        label: "业务员",
        prop: "salesmanName",
        width: 100,
      },
      // render(type) {
      //   return proxy.dictValueLabel(type, userList.value);
      // },
    },
    {
      attrs: {
        label: "下单时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "交期",
        slot: "deliveryTime",
        width: 130,
      },
    },
    {
      attrs: {
        label: "下发生产时间",
        prop: "orderDistributeTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "合同金额",
        slot: "amount",
        width: 140,
        align: "right",
      },
    },
    {
      attrs: {
        label: "生产指示",
        slot: "prodTag",
        "min-width": 240,
      },
    },
    {
      attrs: {
        label: "客户名称",
        slot: "buyCorporationName",
        "min-width": 180,
      },
    },
    {
      attrs: {
        label: "商品数据",
        slot: "product",
        "min-width": 240,
      },
    },
    // {
    //   attrs: {
    //     label: "客户标签",
    //     slot: "tags",
    //     width: 180,
    //   },
    // },
    {
      attrs: {
        label: "是否已结清",
        slot: "isSettled",
        width: 100,
      },
      // render(type) {
      //   return proxy.dictValueLabel(type, isSettled.value);
      // },
    },
    {
      attrs: {
        label: "预付比例",
        slot: "advanceRatio",
        width: 100,
        align: "right",
      },
    },

    {
      attrs: {
        label: "已收款金额",
        prop: "sumClaimMoney",
        width: 100,
        align: "right",
      },
    },
    // {
    //   attrs: {
    //     label: "汇率",
    //     prop: "rate",
    //     width: 80,
    //     align: "right",
    //   },
    //   render(rate) {
    //     return proxy.moneyFormat(rate, 4);
    //   },
    // },
    // {
    //   attrs: {
    //     label: "合同金额（CNY）",
    //     prop: "amountCNY",
    //     width: 160,
    //     align: "right",
    //   },
    //   render(amountCNY) {
    //     return proxy.moneyFormat(amountCNY, 2);
    //   },
    // },
    // {
    //   attrs: {
    //     label: "到账金额（CNY）",
    //     prop: "sumClaimMoney",
    //     width: 160,
    //     align: "right",
    //   },
    //   render(sumClaimMoney) {
    //     return proxy.moneyFormat(sumClaimMoney, 2);
    //   },
    // },
    // {
    //   attrs: {
    //     label: "到账比例",
    //     slot: "scale",
    //     width: 100,
    //     align: "right",
    //   },
    // },

    {
      attrs: {
        label: "审批状态",
        prop: "status",
        width: 100,
      },
      render(type) {
        return proxy.dictValueLabel(type, status.value);
      },
    },

    {
      attrs: {
        label: "操作",
        width: 200,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          row.status == 30 &&
          (row.orderDistributeStatus == 0 || row.orderDistributeStatus == 2)
            ? {
                attrs: {
                  label: "生产",
                  type: "danger",
                  text: true,
                },
                el: "button",
                click() {
                  clickDistributeProduction(row);
                },
              }
            : {},

          route.query.pageType == "1"
            ? {
                attrs: {
                  label: "转销售订单",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  trunContract(row);
                },
              }
            : {},
          // row.status == 30 &&
          // row.outboundStatus == 0 &&
          // row.produceStatus == 2
          //   ? {
          //       attrs: {
          //         label: "销售出库",
          //         type: "primary",
          //         text: true,
          //       },
          //       el: "button",
          //       click() {
          //         proxy
          //           .msgConfirm()
          //           .then((res) => {
          //             proxy
          //               .post("/contract/saleOutbound", {
          //                 id: row.id,
          //               })
          //               .then((res) => {
          //                 proxy.msgTip("操作成功", 1);
          //                 getList();
          //               });
          //           })
          //           .catch((err) => {});
          //       },
          //     }
          //   : {},
          row.status == 30 && row.produceStatus != 10
            ? {
                attrs: {
                  label: "变更",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickAlteration(row);
                },
              }
            : {},

          row.status == 30
            ? {
                attrs: {
                  label: "打印",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickPrint(row);
                },
              }
            : {},
          // row.orderDistributeStatus == 1
          //   ? {}
          //   :
          (row.status == 10 ||
            (row.status == 30 && Number(row.sumClaimMoney) == 0)) &&
          (row.produceStatus == 0 || row.produceStatus == null)
            ? {
                attrs: {
                  label: "作废",
                  type: "danger",
                  text: true,
                },
                el: "button",
                click() {
                  proxy
                    .msgConfirm()
                    .then((res) => {
                      proxy
                        .post("/contract/cancellation", {
                          id: row.id,
                        })
                        .then((res) => {
                          proxy.msgTip("操作成功", 1);

                          getList();
                        });
                    })
                    .catch((err) => {});
                },
              }
            : {},
          row.status == 30 && row.isSettled == "0"
            ? {
                attrs: {
                  label: "结清",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  ElMessageBox.confirm("是否确认结清?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }).then(() => {
                    proxy
                      .post("/contract/settle", {
                        id: row.id,
                      })
                      .then(() => {
                        ElMessage({
                          message: "操作成功",
                          type: "success",
                        });
                        getList();
                      });
                  });
                },
              }
            : {},
          // {
          //   attrs: {
          //     label: "生产指示",
          //     type: "primary",
          //     text: true,
          //   },
          //   el: "button",
          //   click() {
          //     handleEditTag(row);
          //   },
          // },
          row.isSettled == "1"
            ? {
                attrs: {
                  label: "售后",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  openRecords.value = true;
                  getRecordsData(row);
                },
              }
            : {},
        ];
      },
    },
  ];
});
const getDict = () => {
  // proxy
  //   .getDictOne([
  //     "customer_tag",
  //     "trade_mode",
  //     "account_currency",
  //     "shipping_method",
  //   ])
  //   .then((res) => {
  //     customerTag.value = res["customer_tag"].map((x) => ({
  //       label: x.dictValue,
  //       value: x.dictKey,
  //     }));
  //     tradeMethods.value = res["trade_mode"].map((x) => ({
  //       label: x.dictValue,
  //       value: x.dictKey,
  //     }));
  //     accountCurrency.value = res["account_currency"].map((x) => ({
  //       label: x.dictValue,
  //       value: x.dictKey,
  //     }));
  //     shippingMethod.value = res["shipping_method"].map((x) => ({
  //       label: x.dictValue,
  //       value: x.dictKey,
  //     }));
  //   });
  // proxy.post("/corporation/page", { pageNum: 1, pageSize: 999 }).then((res) => {
  //   corporationList.value = res.rows.map((item) => {
  //     return {
  //       ...item,
  //       label: item.name,
  //       value: item.id,
  //     };
  //   });
  // });
  proxy
    .get("/tenantDept/list", {
      pageNum: 1,
      pageSize: 9999,
      keyword: "",
      tenantId: proxy.useUserStore().user.tenantId,
      type: 0,
    })
    .then((res) => {
      companyData.value = res.data.map((x) => ({
        ...x,
        label: x.deptName,
        value: x.deptId,
      }));
    });

  proxy.post("/customer/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    customerList.value = res.rows.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
      };
    });
  });
  proxy
    .get("/tenantUser/list", {
      pageNum: 1,
      pageSize: 10000,
      tenantId: proxy.useUserStore().user.tenantId,
      // companyId: proxy.useUserStore().user.companyId,
    })
    .then((res) => {
      userList.value = res.rows.map((item) => {
        return {
          label: item.nickName,
          value: item.userId,
        };
      });
    });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/contract/page", sourceList.value.pagination).then((res) => {
    res.rows.forEach((x) => {
      // x.addTagShow = false;
      // if (x.tag) {
      //   x.tags = x.tag.split(",");
      // } else {
      //   x.tags = [];
      // }
      if (x.prodTag) {
        x.prodTags = x.prodTag.split(",");
      } else {
        x.prodTags = [];
      }
    });
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });

  // proxy
  //   .post("/contract/getHeadStatistic", sourceList.value.pagination)
  //   .then((res) => {
  //     headerData.value = res;
  //     if (headerData.value) {
  //       headerData.value.sumClaimMoneyOne = parseFloat(
  //         Number(headerData.value.sumAmount) -
  //           Number(headerData.value.sumClaimMoney)
  //       ).toFixed(2);
  //     }
  //   });
};
getDict();
if (route.query.code) {
  sourceList.value.pagination.keyword = route.query.code;
}
getList();
const newContract = () => {
  // let flowKey = route.query.pageType == "1" ? "sample_flow" : "contract_flow" ;
  let flowKey = "contract_flow";
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: flowKey,
      flowName: "订单流程",
      random: proxy.random(),
    },
  });
};
const openPrint = ref(false);
const rowData = ref({});
const clickPrint = (row) => {
  rowData.value = {
    id: row.id,
  };
  openPrint.value = true;
};
const clickDownload = () => {
  proxy.getPdf("外销合同PDF文件");
};
const openHandoverSlip = ref(false);
const handoverSlipForm = ref({
  id: "",
  code: "",
  buyCorporationName: "",
  fileList: [],
  packageFileList: [],
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "code",
      label: "合同编号",
      itemType: "text",
      disabled: true,
    },
    {
      type: "input",
      prop: "buyCorporationName",
      label: "客户名称",
      itemType: "text",
      disabled: true,
    },
    {
      type: "slot",
      slotName: "file",
      label: "交接单",
    },
    {
      type: "slot",
      slotName: "indication",
      label: "包装指示",
    },
  ];
});
const uploadData = ref({});
const indicationUploadData = ref({});
const clickHandoverSlip = (item) => {
  handoverSlipForm.value.id = item.id;
  handoverSlipForm.value.code = item.code;
  handoverSlipForm.value.buyCorporationName = item.buyCorporationName;
  if (item.fileInfoVos && item.fileInfoVos.length > 0) {
    handoverSlipForm.value.fileList = item.fileInfoVos.map((item) => {
      return {
        raw: item,
        name: item.fileName,
        url: item.fileUrl,
      };
    });
  } else {
    handoverSlipForm.value.fileList = [];
  }
  if (item.packageFileInfoVOList && item.packageFileInfoVOList.length > 0) {
    handoverSlipForm.value.packageFileList = item.packageFileInfoVOList.map(
      (item) => {
        return {
          raw: item,
          name: item.fileName,
          url: item.fileUrl,
        };
      }
    );
  } else {
    handoverSlipForm.value.packageFileList = [];
  }
  openHandoverSlip.value = true;
};
const uploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const indicationUploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  indicationUploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const handleSuccess = (any, UploadFile) => {
  UploadFile.raw.uploadState = false;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const submitHandoverSlip = () => {
  if (
    handoverSlipForm.value.fileList &&
    handoverSlipForm.value.fileList.length > 0
  ) {
    for (let i = 0; i < handoverSlipForm.value.fileList.length; i++) {
      if (handoverSlipForm.value.fileList[i].raw.uploadState) {
        return ElMessage("文件上传中,请稍后提交");
      }
    }
  }
  if (
    handoverSlipForm.value.packageFileList &&
    handoverSlipForm.value.packageFileList.length > 0
  ) {
    for (let i = 0; i < handoverSlipForm.value.packageFileList.length; i++) {
      if (handoverSlipForm.value.packageFileList[i].raw.uploadState) {
        return ElMessage("文件上传中,请稍后提交");
      }
    }
  }
  let data = proxy.deepClone(handoverSlipForm.value);
  if (data.fileList && data.fileList.length > 0) {
    data.fileList = data.fileList.map((item) => {
      return {
        id: item.raw.id,
        fileName: item.raw.fileName,
        fileUrl: item.raw.fileUrl,
      };
    });
  } else {
    data.fileList = [];
  }
  if (data.packageFileList && data.packageFileList.length > 0) {
    data.packageFileList = data.packageFileList.map((item) => {
      return {
        id: item.raw.id,
        fileName: item.raw.fileName,
        fileUrl: item.raw.fileUrl,
      };
    });
  } else {
    data.packageFileList = [];
  }
  proxy.post("/contract/contractHandover", data).then(() => {
    ElMessage({
      message: "操作成功！",
      type: "success",
    });
    openHandoverSlip.value = false;
    getList();
  });
};
const addTag = ref("");
const judgeTagSelect = (data, val) => {
  if (data && data.length > 0) {
    if (data.includes(val)) {
      return true;
    }
  }
  return false;
};
const changeTag = (val, item) => {
  let data = {
    id: item.buyCorporationId,
    tag: proxy.deepClone(item.tags),
  };
  data.tag.push(val);
  data.tag = data.tag.join(",");
  proxy.post("/customer/editTag", data).then(() => {
    ElMessage({
      message: "添加成功",
      type: "success",
    });
    item.addTagShow = false;
    addTag.value = "";
    getList();
  });
};
const tagClose = (val, item) => {
  let data = {
    id: item.buyCorporationId,
    tag: proxy.deepClone(item.tags),
  };
  data.tag = data.tag.filter((row) => row !== val);
  if (data.tag && data.tag.length > 0) {
    data.tag = data.tag.join(",");
  } else {
    data.tag = "";
  }
  proxy.post("/customer/editTag", data).then(() => {
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    item.addTagShow = false;
    addTag.value = "";
    getList();
  });
};
const showSelect = (item) => {
  item.addTagShow = true;
};

const currentContractId = ref("");
const openDetails = (row) => {
  // currentContractId.value = row.id;
  // openDetailsDialog.value = true;
  // 新页面打开方式
  // const page = proxy.$router.resolve({
  //   name: "contractDetails",
  //   query: {
  //     currentContractId: row.id,
  //   },
  // });
  // window.open(page.href, "_blank");

  proxy.$router.push({
    name: "contractDetails",
    query: {
      currentContractId: row.id,
    },
  });
};

const computeScale = (item) => {
  let text = 0;
  if (
    item.sumClaimMoney &&
    Number(item.sumClaimMoney) > 0 &&
    item.amountCNY &&
    Number(item.amountCNY) > 0
  ) {
    text = parseFloat(
      (Number(item.sumClaimMoney) / Number(item.amountCNY)) * 100
    ).toFixed(2);
  }
  return text + "%";
};

const clickCorporationName = (row) => {
  proxy.$router.push({
    name: "Portrait",
    query: {
      id: row.buyCorporationId,
    },
  });
};

const printObj = ref({
  id: "pdfDom",
  popTitle: "",
  extraCss:
    "https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.compat.css, https://cdn.bootcdn.net/ajax/libs/hover.css/2.3.1/css/hover-min.css",
  extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
});

const clickAlteration = (row) => {
  // let flowKey =
  //   route.query.pageType == "1" ? "sample_update_flow" : "contract_update_flow";
  let flowKey = "contract_update_flow";
  proxy.$router.push({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: flowKey,
      flowName: "订单变更流程",
      random: proxy.random(),
      businessId: row.id,
    },
  });
};

const PdfDom = ref(null);
const exportExcel = () => {
  PdfDom.value.exportExcel();
};

const formData = reactive({
  recordsFormData: {},
  data: {},
  tagData: {},
});
const formLoading = ref(false);
const openRecords = ref(false);
const openAddRecords = ref(false);
const recordsLoading = ref(false);
const recordsData = ref([]);
const recordsForm = ref(null);
const rowContractData = ref({});
const recordsFormConfig = computed(() => [
  {
    type: "date",
    itemType: "datetime",
    prop: "documentaryTime",
    label: "售后时间",
    disabled: false,
  },

  {
    type: "input",
    prop: "documentaryRemark",
    label: "售后记录",
    itemType: "textarea",
    disabled: false,
  },
  {
    type: "slot",
    slotName: "file",
    label: "上传附件",
  },
]);
const recordsRules = ref({
  documentaryTime: [
    { required: true, message: "请选择售后时间", trigger: "change" },
  ],
  documentaryRemark: [
    { required: true, message: "请输入售后记录", trigger: "blur" },
  ],
});
const getRecordsData = (row) => {
  if (row && row.id) {
    rowContractData.value = row;
  }
  proxy
    .post("/contractDocumentary/page", {
      businessId: rowContractData.value.id,
      documentaryType: "-2",
    })
    .then((res) => {
      recordsData.value = res.rows;
      const idList = recordsData.value.map((x) => x.id);
      // 请求文件数据并回显
      if (idList.length > 0) {
        proxy
          .post("/fileInfo/getList", {
            businessIdList: idList,
          })
          .then((fileObj) => {
            if (fileObj) {
              for (let i = 0; i < recordsData.value.length; i++) {
                const e = recordsData.value[i];
                for (const key in fileObj) {
                  if (e.id === key) {
                    e.fileList = fileObj[key];
                  }
                }
              }
            }
          });
      }
    });
};
const handleClickAddRecord = () => {
  formData.recordsFormData = {
    businessId: rowContractData.value.id,
    businessType: "0",
    documentaryType: "-2",
    documentaryTime: proxy.parseTime(new Date()),
    documentaryRemark: "",
    fileList: [],
  };
  openAddRecords.value = true;
};

const submitRecords = () => {
  recordsForm.value.handleSubmit(() => {
    formLoading.value = true;
    formData.recordsFormData.fileList = formData.recordsFormData.fileList.map(
      (item) => {
        return {
          id: item.raw.id,
          fileName: item.raw.fileName,
          fileUrl: item.raw.fileUrl,
          uploadState: item.raw.uploadState,
        };
      }
    );
    proxy
      .post("/contractDocumentary/add", formData.recordsFormData)
      .then((res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        formLoading.value = false;
        openAddRecords.value = false;
        getRecordsData();
      });
  });
};
const openFile = (item) => {
  window.open(item.fileUrl, "_blank");
};

const formSearchConfig = computed(() => {
  return [
    {
      type: "select",
      label: "审批状态",
      prop: "status",
      itemWidth: 50,
      data: status.value,
      clearable: true,
    },
    {
      type: "select",
      label: "工厂",
      prop: "companyId",
      itemWidth: 50,
      data: companyData.value,
      clearable: true,
    },
    {
      type: "select",
      label: "业务员",
      prop: "userId",
      data: userList.value,
      clearable: true,
    },
    {
      type: "date",
      itemType: "datetime",
      label: "合同时间",
      prop: "beginTime",
      placeholder: "合同开始时间",
      itemWidth: 50,
      clearable: true,
    },
    {
      type: "date",
      itemType: "datetime",
      label: " ",
      prop: "endTime",
      placeholder: "合同结束时间",
      itemWidth: 50,
      clearable: true,
    },
  ];
});
const moreSearchDialog = ref(false);
const clickMoreSearch = () => {
  moreSearchDialog.value = true;
};
const moreSearchQuery = () => {
  moreSearchDialog.value = false;
  getList();
};
const moreSearchReset = () => {
  sourceList.value.pagination = {
    total: 0,
    pageNum: sourceList.value.pagination.pageNum,
    pageSize: sourceList.value.pagination.pageSize,
    keyword: "",
    status: "",
    sellCorporationId: "",
    beginTime: "",
    endTime: "",
  };
  moreSearchQuery();
};
const productionFormDom = ref(null);
const productionDialog = ref(false);
const productionFormConfig = computed(() => [
  {
    type: "treeSelect",
    prop: "produceCompanyId",
    label: "工厂",
    data: companyData.value,
    propsTreeLabel: "deptName",
    propsTreeValue: "deptId",
    itemWidth: 100,
    disabled: true,
  },
  {
    type: "input",
    itemType: "textarea",
    label: "驳回原因",
    prop: "rejectRemark",
    itemWidth: 100,
    isShow: formData.data.rejectRemark ? true : false,
    disabled: true,
  },
  {
    type: "date",
    itemType: "datet",
    label: "交期",
    prop: "deliveryPeriod",
    // placeholder: "合同开始时间",
    itemWidth: 100,
    disabledFn: (date) => {
      return moment(date).isBefore(moment());
    },
    clearable: true,
  },
]);
const productionRules = ref({
  produceCompanyId: [
    { required: true, message: "请选择生产公司", trigger: "change" },
  ],
  deliveryPeriod: [
    { required: true, message: "请选择交期", trigger: "change" },
  ],
});
const clickDistributeProduction = (row) => {
  formData.data = {
    contractId: row.id,
    deliveryPeriod: "",
    produceCompanyId: row.companyId,
    rejectRemark: row.rejectRemark,
    orderDistributeStatus: row.orderDistributeStatus,
  };
  productionDialog.value = true;
};
const submitProduction = () => {
  productionFormDom.value.handleSubmit(() => {
    let url =
      formData.data.orderDistributeStatus == 1
        ? "/produceOrder/editDeliveryPeriod"
        : "/produceOrder/createOrder";
    formLoading.value = true;
    proxy.post(url, formData.data).then((res) => {
      proxy.msgTip("操作成功");
      formLoading.value = false;
      productionDialog.value = false;
      getList();
    });
  });
};

const handleEditTag = (row) => {
  formData.tagData = {
    id: row.id,
    prodTag: row.prodTags,
  };
  tagDialog.value = true;
};
const tagFormDom = ref(null);
const tagDialog = ref(false);
const tagFormConfig = computed(() => [
  {
    type: "select",
    prop: "prodTag",
    label: "生产指示",
    multiple: true,
    data: contractTag.value,
    itemWidth: 100,
  },
  {
    type: "input",
    prop: "prodRemark",
    itemType: "textarea",
    label: "备注",
    itemWidth: 100,
  },
]);
const tagRules = ref({
  prodTag: [{ required: true, message: "请选择生产指示", trigger: "change" }],
});
const submitTag = () => {
  tagFormDom.value.handleSubmit(() => {
    const data = {
      id: formData.tagData.id,
      prodTag: formData.tagData.prodTag.join(","),
      prodRemark: formData.tagData.prodRemark,
    };
    formLoading.value = true;
    proxy.post("/contract/updateProductionTag", data).then((res) => {
      proxy.msgTip("操作成功");
      formLoading.value = false;
      tagDialog.value = false;
      getList();
    });
  });
};

const prodTagClose = (index, row) => {
  row.prodTags.splice(index, 1);
  proxy
    .post("/contract/updateProductionTag", {
      id: row.id,
      prodTag: row.prodTags.join(","),
    })
    .then((res) => {});
};

const handleClickFile = (fileUrl) => {
  window.open(fileUrl, "_blank");
};
const productData = ref([]);
const onShowProductData = (item) => {
  productData.value = item.contractProductList;
};

onMounted(() => {
  $bus.on("refreshTableData", () => {
    getList();
  });
});

onBeforeUnmount(() => {
  // 取消订阅特定事件
  $bus.off("refreshTableData");
});
const trunContract = (row) => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "contract_flow",
      flowName: "转销售订单",
      random: proxy.random(),
      businessId: row.id,
    },
  });
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
.baseRow {
  min-height: 24px;
  border-top: 1px solid black;
  border-left: 1px solid black;
}
.contentRow {
  border-right: 1px solid black;
  line-height: 24px;
  padding-left: 4px;
}
.active {
  background: #a6dd82;
  color: #fff;
  border-radius: 4px;
}
.more {
  position: absolute;
  left: -60px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  opacity: 0.5;
  height: 65px;
  padding-top: 8px;
  width: 50px;
  border-radius: 3px;
  text-align: center;
  cursor: pointer;
  pointer-events: none;
}
</style>
