<template>
  <basic-container>
    <avue-crud
      :option="option"
      v-model:search="search"
      v-model:page="page"
      v-model="form"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left="{}">
        <el-button
          type="primary"
          icon="el-icon-plus"
          plain
          v-if="permission.basicdataFreight_add"
          @click="ownSave"
          >新增
        </el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          plain
          v-if="permission.basicdataFreight_delete"
          @click="handleDelete"
          >删 除
        </el-button>

        <!--        <el-button type="warning"-->
        <!--                   plain-->
        <!--                   icon="el-icon-download"-->
        <!--                   @click="handleExport">导 出-->
        <!--        </el-button>-->
      </template>
      <!--      <template  #menu="{row,index,size}">-->
      <!--        <el-button type="danger"-->
      <!--                   icon="el-icon-plus"-->
      <!--                   @click="$refs.crud.rowAdd()">新增</el-button>-->
      <!--      </template>-->
    </avue-crud>
    <el-dialog   v-model="Detailspop" title="详情" width="60%">
      <el-form
      v-loading="Formloading"
        class="el_formInfo"
        :model="formInfo"
        label-width="300px"
        style="width: 100%"
        disabled
      >
        <div class="el_box_1">
          <el-form-item label="客户名称">
            <el-input v-model="formInfo.clientName" />
          </el-form-item>

          <el-form-item label="品牌名称">
            <el-input v-model="formInfo.brand" />
          </el-form-item>

          <el-form-item label="一口价">
            <el-input v-model="formInfo.fixedPrice" />
          </el-form-item>

          <el-form-item label="品类">
            <el-input v-model="formInfo.categoryName" />
          </el-form-item>
        </div>
        <div class="el_box_2">
          <el-form-item label="生效时间">
            <el-input v-model="formInfo.effectiveTime" />
          </el-form-item>
          <el-form-item label="截止时间">
            <el-input v-model="formInfo.expirationTime" />
          </el-form-item>

          <el-form-item label="服务类型">
            <el-input v-model="formInfo.details" />
          </el-form-item>
        </div>
      
      <el-tabs type="border-card">
        <el-tab-pane label="干线">
          <div class="el_groundline" v-for="item in groundlineZd" :key="item.dictKey">
            <div class="checkbox checked" v-if="item.cost !=null"></div>
            <el-form-item :label="item.label + '金额'">
              <el-input :value="item.cost ? item.cost : '暂无'"  disabled/>
            </el-form-item>

            <el-form-item label="单位">
              <el-input :value="item.formulaModeName ? item.formulaModeName : '暂无'"  disabled/>
            </el-form-item>
          </div>
        </el-tab-pane>
        <el-tab-pane label="仓库">
          <div class="el_groundline_box">
          <div class="el_groundline" v-for="item in warehouseZd" :key="item.dictKey">
            <div class="checkbox checked" v-if="item.cost !=null"></div>
            <el-form-item :label="item.label + '金额'">
              <el-input :value="item.cost ? item.cost : '暂无'"  disabled/>
            </el-form-item>

            <el-form-item label="单位">
              <el-input :value="item.formulaModeName ? item.formulaModeName : '暂无'"  disabled/>
            </el-form-item>
          </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="配送">
          <div class="el_groundline_box">
            <div class="el_groundline" v-for="item in DeliveryZd" :key="item.dictKey">
              <div class="checkbox checked" v-if="item.cost !=null"></div>
              <el-form-item :label="item.label + '金额'">
                <el-input :value="item.cost ? item.cost : '暂无'"  disabled/>
              </el-form-item>

              <el-form-item label="单位">
                <el-input :value="item.formulaModeName ? item.formulaModeName : '暂无'"  disabled/>
              </el-form-item>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Detailspop = false">关闭</el-button>
          <!-- <el-button type="primary" @click="DetailspopFn">
          确定
        </el-button> -->
        </div>
      </template>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  $_QueryUserName,
  $_brand,
  $_category,
  $_getDeptLazyTree,
} from '@/api/basicdata/basicdataFreight';
// import option from "@/option/basicdata/basicdataFreight";
import { mapGetters } from 'vuex';
import { exportBlob } from '@/api/common';
import { getDictionaryBiz } from '@/api/system/dict'; //字典
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      Detailspop: false,
      Formloading:false,
      formInfo: {}, //详情弹窗表格
      groundlineZd: [], //干线
      warehouseZd: [], //仓库
      DeliveryZd: [], //配送
      groundlineInfo: [], //干线
      warehouseInfo: [], //仓库
      DeliveryInfo: [], //配送
      page: {
        pageSize: 30,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        labelWidth: 120,
        addBtn: false, //添加按钮
        tip: false,
        searchShow: false,
        searchMenuSpan: 7,
        indexLabel: '序号',
        indexWidth: '100',
        align: 'center',
        border: true,
        indexFixed: false,
        index: true,
        width: '100%',
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        column: [
          {
            label: '租户号',
            prop: 'tenantId',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '创建人',
            prop: 'createUser',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '创建时间',
            prop: 'createTime',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '更新人',
            prop: 'updateUser',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '状态',
            prop: 'status',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '是否已删除',
            prop: 'isDeleted',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '创建部门',
            prop: 'createDept',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '主键',
            prop: 'id',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '预留1',
            prop: 'reserve1',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '预留2',
            prop: 'reserve2',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '预留3',
            prop: 'reserve3',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '预留4',
            prop: 'reserve4',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '预留5',
            prop: 'reserve5',
            type: 'input',
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
            width: 'fit-content',
          },
          {
            label: '计算方式', //;1件  2方  3公斤
            prop: 'formulaMode',
            type: 'select',
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=basic_freight_formulamode',
            width: '100px',
            span: 12,
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            search: true,
            rules: [
              {
                required: true,
                message: '请选择计算方式',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '物品名称',
            prop: 'itemName',
            type: 'input',
            width: '150px',
            span: 12,
            rules: [
              {
                required: true,
                message: '请填写物品名称',
                trigger: 'blur',
              },
            ],
          },
          // {
          //   label: "门店品牌",
          //   prop: "storeBrandId",
          //   type: "select",
          //   width:"150px",
          //   span:12,
          //   allowCreate: true,
          //   filterable: true,
          //   dicUrl: "/api/logpm-basicdata/basicdataStoreBrand/listName?name={{key}}",
          //   props: {
          //     label: 'storeBrandName',
          //     value: 'id'
          //   },
          //   change: (val) => {
          //
          //     // let dic =  val.dic;
          //     if(!!val.value){
          //       // console.log(">>>>。。。。",val);
          //       let d = [];
          //       let a = [];
          //       val.dic.forEach(i =>{
          //         if(i.id == val.value){
          //           console.log("iiiiii",i);
          //           let dataZhi = {
          //             label: i.brandName,
          //             value: i.brandId
          //           }
          //           let data = {
          //             label: i.storeName,
          //             value: i.shopId
          //           }
          //           d.push(dataZhi);
          //           a.push(data);
          //         }
          //       })
          //       // this.selectionChange();
          //       // console.log(",.,.",this.option.column[26]);
          //       this.fuzhi(d,a);
          //
          //
          //     }
          //   },
          //   rules: [{
          //     required: true,
          //     message: '请选择门店品牌',
          //     trigger: 'blur'
          //   }]
          //
          // },

          {
            label: '门店',
            prop: 'shop',
            type: 'select',
            search: false,
            dicData: [],
            disabled: true,
          },
          {
            label: '品牌',
            prop: 'brand',
            type: 'select',
            search: false,
            dicData: [],
            disabled: true,
          },
          {
            label: '服务类型', //;1 干  2干仓  3干仓配 4干配
            prop: 'typeService',
            type: 'select',
            width: '150px',
            span: 12,
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=basic_freight_type',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            search: true,
            rules: [
              {
                required: true,
                message: '请选择服务类型',
                trigger: 'blur',
              },
            ],
          },

          {
            label: '一级品类',
            prop: 'firstClassCategory',
            type: 'input',
            width: '150px',
            span: 12,
            rules: [
              {
                required: true,
                message: '请填写一级品类',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '一口价',
            prop: 'fixedPrice',
            type: 'input',
            width: '150px',
            span: 12,
            rules: [
              {
                required: true,
                message: '请填写一口价',
                trigger: 'blur',
              },
            ],
          },

          {
            label: '生效时间',
            prop: 'effectiveTime',
            type: 'datetime',
            width: '150px',
            span: 12,
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            rules: [
              {
                required: true,
                message: '请填写生效时间',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '截止时间',
            prop: 'expirationTime',
            type: 'datetime',
            width: '150px',
            span: 12,
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            rules: [
              {
                required: true,
                message: '请填写截止时间',
                trigger: 'blur',
              },
            ],
          },
          // {
          //   label: "类型",
          //   prop: "type",
          //   type: "input",
          // },
          // {
          //   label: "标识",
          //   prop: "identification",
          //   type: "input",
          //
          // },
          {
            label: '时间段', //;1 0-30天  2 0-60天 3 60天以上
            prop: 'warehousingTimeCharge',
            type: 'select',
            width: '150px',
            span: 12,
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=basic_freight_timecharge',
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            search: true,
            rules: [
              {
                required: true,
                message: '请选择时间段',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '时间段费用',
            prop: 'warehousingTimeStatus',
            type: 'input',
            width: '150px',
            span: 12,
            rules: [
              {
                required: true,
                message: '请填写时间段费用',
                trigger: 'blur',
              },
            ],
          },
        ],
      },
      data: [],
    };
  },
  created() {
    // 字典公共函数
    //   updateDictionary(targetArray, dictionaryType) {
    //   getDictionaryBiz(dictionaryType).then(res => {
    //     console.log(res, '字典');
    //     res.data.data.forEach(item => {
    //       targetArray.push({
    //         value: item.dictKey,
    //         label: item.dictValue,
    //       });
    //     });
    //   });
    // };
    // groundlineZd:[],//干线
    //   warehouseZd:[],//仓库
    //   DeliveryZd:[],//配送

    getDictionaryBiz('artery').then(res => {
      console.log(res, '干线字典');
      res.data.data.forEach(item => {
        this.groundlineZd.push({
          value: item.dictKey,
          label: item.dictValue,
        });
      });
    });

    getDictionaryBiz('entrepot').then(res => {
      console.log(res, '仓库字典');
      res.data.data.forEach(item => {
        this.warehouseZd.push({
          value: item.dictKey,
          label: item.dictValue,
        });
      });
    });
    getDictionaryBiz('delivery').then(res => {
      console.log(res, '配送字典');
      res.data.data.forEach(item => {
        this.DeliveryZd.push({
          value: item.dictKey,
          label: item.dictValue,
        });
      });
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.basicdataFreight_add, false),
        viewBtn: this.validData(this.permission.basicdataFreight_view, false),
        delBtn: this.validData(this.permission.basicdataFreight_delete, false),
        editBtn: this.validData(this.permission.basicdataFreight_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    fuzhi(led, ed) {
      // console.log(">>>>",led,ed);
      this.option.column[27].dicData = led;
      this.option.column[27].value = led[0].value;
      this.option.column[26].dicData = ed;
      this.option.column[26].value = ed[0].value;
      this.form.shop = ed[0].value;
      this.form.brand = led[0].value;
    },
    ownSave() {
      this.$router.push({
        path: '/basicdata/brand/basicdataFreightFrom',
        query: {},
      });
    },
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleExport() {
      let downloadUrl = `/blade-basicdataFreight/basicdataFreight/export-basicdataFreight?${
        this.website.tokenHeader
      }=${getToken()}`;
      const {
        formulaMode,
        singleColon,
        forwardingUnit,
        shop,
        brand,
        typeService,
        clearingForm,
        warehousingTimeCharge,
      } = this.query;
      let values = {
        formulaMode_equal: formulaMode,
        singleColon_like: singleColon,
        forwardingUnit_like: forwardingUnit,
        shop_like: shop,
        brand_like: brand,
        typeService_equal: typeService,
        clearingForm_equal: clearingForm,
        warehousingTimeCharge_: warehousingTimeCharge,
      };
      this.$confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportBlob(downloadUrl, values).then(res => {
          downloadXls(res.data, `基础价格记录表${dateNow()}.xlsx`);
          NProgress.done();
        });
      });
    },
    
 enrichDictionaryWithCosts(dictionary, dataArray, itemNameField) {
    dictionary.forEach(dictItem => {
      console.log(dictItem,'dictItem');
        dataArray.forEach(dataItem => {
            if (dictItem.label === dataItem[itemNameField]) {
                dictItem.formulaModeName = dataItem.formulaModeName;
                dictItem.cost = dataItem.cost;
            }
        });
    });
},
    // 查看按钮
    beforeOpen(done, type) {
      this.Detailspop = true; //开启弹窗
      this.Formloading=true
      this.formInfo={}
      getDetail(this.form.id).then(res => {
        console.log(res, 'res');
        this.form = res.data.data;
        this.formInfo.fixedPrice =
          this.form.fixedPrice == 1 ? '否' : this.form.fixedPrice == 2 ? '是' : '暂无';
        this.formInfo.categoryName = this.form.categoryName; //品类
        this.formInfo.effectiveTime = this.form.effectiveTime; //生效时间
        this.formInfo.expirationTime = this.form.expirationTime; //截止时间
        this.formInfo.details = res.data.data.details.map(res => res.typeName).join(','); //服务类型
        res.data.data.details.forEach(res => {
          if (res.typeName == '干线') {
            this.groundlineInfo.push(res);
          } else if (res.typeName == '仓库') {
            this.warehouseInfo.push(res);
          } else if (res.typeName == '配送') {
            this.DeliveryInfo.push(res);
          }
        });
      this.enrichDictionaryWithCosts( this.groundlineZd,this.groundlineInfo, 'itemName');
      this.enrichDictionaryWithCosts( this.DeliveryZd, this.DeliveryInfo,'itemName');
      this.enrichDictionaryWithCosts(this.warehouseZd,this.warehouseInfo,  'itemName');
      $_QueryUserName({
          id: res.data.data.itemName,
        }).then(res => {
          this.formInfo.clientName = res.data.data.clientName;
          console.log(res, '客户名称');
        });
        // 查询品牌
        $_brand({
          brandId: this.form.brand,
          id: this.form.itemName,
        }).then(res => {
          console.log(res, '品牌');
          this.formInfo.brand = res.data.data.brandName;
        });
        this.Formloading=false;
        return;
        $_category({
          id: this.form.category,
        }).then(res => {
          console.log(res, '品类');
        });
      });
      return;
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          $_QueryUserName({
            id: res.data.data.itemName,
          }).then(res => {
            this.formInfo.clientName = res.data.data.clientName;
            console.log(res, '客户名称');
          });
        });
      }
      done();
    },

    



    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      console.log('>>>>>>>>', params, done);
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      console.log('执行了》》》》》》', list);
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {
        formulaMode,
        singleColon,
        forwardingUnit,
        shop,
        brand,
        typeService,
        clearingForm,
        warehousingTimeCharge,
      } = this.query;

      let values = {
        formulaMode_equal: formulaMode,
        singleColon_like: singleColon,
        forwardingUnit_like: forwardingUnit,
        shop_like: shop,
        brand_like: brand,
        typeService_equal: typeService,
        clearingForm_equal: clearingForm,
        warehousingTimeCharge_: warehousingTimeCharge,
      };

      getList(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style scoped lang="scss">
:deep(.el-form-item__content) {
}
:deep(.avue-form__row) {
  margin-left: 10px;
  max-width: 300px !important;
}
:deep(.no-print) {
  margin-left: auto;
}
:deep(.avue-form__row) {
  margin-left: 0;
}
:deep(.el-form-item__label) {
  padding-left: 0;
  width: auto !important;
}
:deep(.no-print) {
  .el-button {
    margin-right: 0;
  }
}
.el_formInfo {
  display: flex;
  flex-direction: column;
  .el_box_1,
  .el_box_2 {
    display: flex;
  }
}
.el_groundline {
  display: flex;
}
.el_groundline_box{
  display: flex;
  flex-wrap: wrap;
  .el_groundline{
    width: 50%;
  }
}

.checkbox {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 15px;
  border: 1px solid orange;
  margin-top: 8px;
  cursor: pointer;
  border-radius: 2px;
}

.checkbox::after {
  content: '';
  position: absolute;
  top: 40%;
  left: 34%;
  width: 5px;
  height: 10px;
  border-style: solid;
  border-color: orange;
  border-width: 0 2px 2px 0;
  transform: translateY(-50%) rotate(45deg);
  opacity: 0; /* 初始时勾隐藏 */
}

.checkbox.checked::after{
  opacity: 1; /* 勾显示 */
}
</style>
